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;
}
4

2 回答 2

4

PHP 数组是有序的键值存储。这意味着键有一个顺序,即它们被添加到数组中的顺序(或拼接在一起或排序或任何确定顺序)。foreach以这种固有的内置顺序遍历数组。

我不知道这是否与 C 中的任何内容相比。PHP 的数组是其更独特的功能之一。大多数语言都有键值存储(字典/哈希)有序数组(列表)。PHP 已将键值存储作为其唯一的数组类型。

于 2012-12-11T18:12:04.713 回答
0

该数组是在您添加键/值对时形成的,请看这里。因此,foreach也按该顺序遍历。

for($i;$i<$arrayLength;$i++)然而,您正在将它与您指定的循环进行比较index,因此,它总是会搜索该键,然后打印其相应的值。

编辑: 解释上述内容的示例。

于 2012-12-11T17:54:43.437 回答