slevin slevin - 1 month ago 14
PHP Question

for loop does not traverse the whole array in 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

, 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

The same problem occurs even if I replace
. Or
. Why does it stop and does not traverse the whole array? What am I missing here?


Answer Source

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):

$originalarray = range(0, 100, 5);//works

function customreverse($x){
  for($a=0; $a<$origSize; $a++){
    $reversearray[$a] = array_pop($x);
  return($reversearray);//stops at 50 (Now it doesn't)