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 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器