Skip to content

Commit 672325e

Browse files
017-adding-examples-for-loops.php
1 parent 6a945ac commit 672325e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

017-adding-examples-for-loops.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
for($i = 0; $i < 10; $i++) {
4+
echo $i . "\n";
5+
}
6+
7+
$fruits = ["apple", "banana", "orange"];
8+
for($i = 0; $i < count($fruits); $i++) {
9+
echo $fruits[$i] . "\n";
10+
}
11+
12+
$myArray = [
13+
"fruits" => ["apple", "banana", "orange"],
14+
"vegetables" => ["carrot", "potato", "onion"],
15+
"meat" => ["beef", "pork", "chicken"],
16+
"dairy" => ["milk", "yogurt", "cheese"],
17+
"drinks" => ["water", "tea", "coffee"],
18+
"food" => ["pizza", "burger", "salad"],
19+
"sports" => ["tennis", "soccer", "basketball"]
20+
];
21+
// Using a for loop with a pre-calculated array length to iterate through the array.
22+
// // This approach stores the array length in a variable ($iMax) to avoid recalculating it on each iteration, improving performance.
23+
$keys = array_keys($myArray);
24+
for($i = 0, $iMax = count($myArray); $i < $iMax; $i++) {
25+
echo $keys[$i] . " => ";
26+
for($j = 0, $jMax = count($myArray[$keys[$i]]); $j < $jMax; $j++) {
27+
echo $myArray[$keys[$i]][$j] . ", ";
28+
}
29+
echo "\n";
30+
}

0 commit comments

Comments
 (0)