downloadbooks_2014 2017-08-27 13: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 13: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部