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?
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;
}
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.
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.