How to reverse an array in php WITHOUT using the array reverse method How to reverse an array in php WITHOUT using the array reverse method arrays arrays

How to reverse an array in php WITHOUT using the array reverse method


<?php  $array = array(1, 2, 3, 4);  $size = sizeof($array);  for($i=$size-1; $i>=0; $i--){      echo $array[$i];  }?>


Below is the code to reverse an array, The goal here is to provide with an optimal solution. Compared to the approved solution above, my solution only iterates for half a length times. though it is O(n) times. It can make a solution little faster when dealing with huge arrays.

<?php  $ar = [34, 54, 92, 453];  $len=count($ar);  for($i=0;$i<$len/2;$i++){    $temp = $ar[$i];    $ar[$i] = $ar[$len-$i-1];    $ar[$len-$i-1] = $temp;  }  print_r($ar)?>


The problem with your method is when you reach 0, it runs once more and index gets the value of -1.

$reverseArray = array(1, 2, 3, 4);$arraySize = sizeof($reverseArray);for($i=$arraySize-1; $i>=0; $i--){    echo $reverseArray[$i];}