duanquanhan2333 2012-12-11 17:51
浏览 87
已采纳

foreach如何遍历数组?

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;
}
  • 写回答

2条回答 默认 最新

  • dongming0505 2012-12-11 18:12
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog