Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is an array in a PHP foreach loop read?

Tags:

We have all heard of how in a for loop, we should do this:

for ($i = 0, $count = count($array); $i < $c; ++$i) {     // Do stuff while traversing array } 

instead of this:

for ($i = 0; $i < count($array); ++$i) {     // Do stuff while traversing array } 

for performance reasons (i.e. initializing $count would've called count() only once, instead of calling count() with every conditional check).

Does it then also make a difference if, in a foreach loop, I do this:

$array = do_something_that_returns_an_array();  foreach ($array as $key => $val) {     // Do stuff while traversing array } 

instead of this:

foreach (do_something_that_returns_an_array() as $key => $val) {     // Do stuff while traversing array } 

assuming circumstances allow me to use either? That is, does PHP call the function only once in both cases, or is it like for where the second case would call the function again and again?

like image 796
BoltClock Avatar asked Nov 06 '09 05:11

BoltClock


People also ask

Can you use a foreach loop on an array?

The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.

What is foreach of array in PHP?

The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if you try to use it with the variables of different datatype. The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an array.


1 Answers

foreach() is implemented using iterators - thus it only calls the function that returns an array once, and then uses the iterator which points to the existing result set to continue with each item.

like image 101
Amber Avatar answered Sep 22 '22 04:09

Amber