downloadbooks_2014 2017-08-27 21:06
浏览 38
已采纳

for循环不会遍历PHP中的整个数组

I use PHP/7.2.0beta3. So I want to create a custom function to reverse an array in PHP. If the array is (1,2,3) the functions turns it to (3,2,1).

I thought I should use the array_pop, grab the last value of the array and pass it to another array.

The problem

Here is the code I wrote. Just copy it and run it as PHP. I dont know why it stops in the middle of the array and does not continue till the end.

$originalarray = range(0, 100, 5);//works
echo '<br> original array <br>';
print_r($originalarray); // 0-100, with 5 step

function customreverse($x){
    echo '<br> original array in function <br>';
    print_r($x); //works, 0-100, with 5 step
    echo '<br> sizeof in function '.sizeof($x).'<br>'; //works, is 21
    for($a=0; $a<sizeof($x); $a++){
        $reversearray[$a] = array_pop($x);
        echo '<br> reversearray in for loop <br>';
        print_r($reversearray);//stops at 50
        echo '<br> a in for loop <br>';
        echo $a;//stops at 10
    }   

    echo '<br> reverse in function <br>';
    print_r($reversearray);////stops at 50
}
customreverse($originalarray);

The same problem occurs even if I replace sizeof with count. Or $a<sizeof($x) with $a<=sizeof($x). Why does it stop and does not traverse the whole array? What am I missing here?

Thanks

  • 写回答

2条回答 默认 最新

  • dtr32221 2017-08-27 21:20
    关注

    sizeof (or count) is evaluated on every iteration of the loop and the array shrinks on each iteration. You need to store the original count in a variable. For Example (I removed a few lines to focus on the issue):

    <?php
    $originalarray = range(0, 100, 5);//works
    
    function customreverse($x){
      $origSize=sizeof($x);
      for($a=0; $a<$origSize; $a++){
        $reversearray[$a] = array_pop($x);
      }   
      return($reversearray);//stops at 50 (Now it doesn't)
    }
    print_r(customreverse($originalarray));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势