2

From what I have found foreach traverses array in the order of adding elements. See this code:

$array = array();
$array[0] = "me0";
$array[1] = "me1";
$array[2] = "me2";
$array[4] = "me4";
$array[5] = "me5";

//changing
$array[3] = "me3Changed";

foreach($array as $item)
{
    echo $item.'<br />';
}

echo '<br />';
ksort($array);

foreach($array as $item)
{
    echo $item.'<br />';
}

which outputs:

me0
me1
me2
me4
me5
me3Changed

me0
me1
me2
me3Changed
me4
me5

This shows that the array is not traversed in a way for($i;$i<$arrayLength;$i++) how is it traversed than? Assuming that php is written in C++ it should be using some c++ functions that do it this way. Can anyone explain to me how does foreach traverse arrays?


C++ example of traversing array by index:
std::string arr[10]; 
arr[0] = "me0";
arr[1] = "me1";
arr[2] = "me2";
arr[4] = "me4";
arr[5] = "me5";

//changing
arr[3] = "me3Changed";

for(int x = 0; x < 6;x++)
{
    std::cout << arr[x] << std::endl;
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    Trying to rationalise PHP's behaviour in terms of what may or may not be its underlying implementation in some other language is a fool's errand. – Lightness Races in Orbit Dec 11 '12 at 18:14
  • relevant to understanding foreach's order http://stackoverflow.com/questions/11487374/does-php-conserver-order-in-associative-array/11487417#11487417 – goat Dec 11 '12 at 19:14

2 Answers2

4

PHP arrays are ordered key-value stores. Meaning the keys have an order, which is the order in which they were added to the array (or spliced together or sorted or whatever determined the order). foreach traverses arrays in this inherent, built-in order.

I don't know if this compares to anything in C. PHP's arrays are one of its more unique features. Most languages have key-value stores (dictionaries/hashes) or ordered arrays (lists). PHP has ordered key-value stores as its only array type.

deceze
  • 510,633
  • 85
  • 743
  • 889
0

The array is formed as you add in the key/value pair, look here. Hence, foreach traverses in that order as well.

Whereas, you are comparing it with a loop for($i;$i<$arrayLength;$i++) where you are specifying the index, hence, its ALWAYS going to search for that key, and then print its corresponding value.

Edit: Example explaining the above.

Teena Thomas
  • 5,139
  • 1
  • 13
  • 17