Reputation: 710
The questions that I saw asked on this topic mainly revolved around performance/speed comparisons. I'm very familiar with JavaScript for
loops and how to approach them when using arrays, for example (and I know this topic isn't about JavaScript, but just writing this to show my understanding of loops/arrays up to now):
var arr = [1,3,5];
for (var i=0; i<2; i++) {
console.log(arr[i]);
}
PHP is telling me that for arrays, I should navigate them using foreach
loops. But both of the below loop styles below produce the same result.
<?php
$arr = array(1,3,5);
foreach($arr as $numbers) {
echo "Number is: {$numbers}<br>";
}
for ($i=0; $i<=2; $i++) {
echo "Number is: " . $arr[$i] . "<br>";
}
?>
I understand that the summary of a standard response is "Well there's more to it than that." Can someone quickly explain the overall benefit to using foreach
for arrays over for
and if it is has other applications outside of arrays?
Upvotes: 1
Views: 75
Reputation: 71
Consider the following code:
$arrayItems = (count($array) - 1);
for ($i = 0, $i <= $arrayItems; $i++) {
echo $array[$i];
}
If the array keys are associative using a string or some sort of "id" for keys (this is typical when iterating arrays of DB results), then that code doesn't work. Using foreach will cover the use cases.
If memory serves, foreach might be a fractional bit faster, under the hood, as well.
Upvotes: 1