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
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));
jh1711 properly explained that your loop ends early because the middle statement in for(statement1; statement2; statement3)
gets executed each iteration, and because you're popping the original array within the loop, sizeOf()
returns a smaller number each time.
You could compact your code a bit, by building your reverse array like so:
while(!empty($original)) $reverse[] = array_pop($original);
If you want to preserve key=>value
bindings (meaning reverse keys as well, so that the same keys will bind to the same values), you could do:
while(!empty($original)):
$val = end($original); // set pointer at end of array
$reverse[key($original)] = $val;
endwhile;
If you want to modify the array in-place (not create a 2nd array), you could do:
for($i=0, $j=sizeof($original); $i < $j; $i++){
array_splice($original,$i,0,array_pop($original));
} // pop last element and insert it earlier in the array