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 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画