I want to know how to reverse an array without using the array_reverse method. I have an array called reverse array which is the one i want to reverse. My code is below. could someone point out what i am doing wrong as I cannot find any example of reversing an array this way anywhere else. my code is below.
<?php
//Task 21 reverse array
$reverseArray = array(1, 2, 3, 4);
$tmpArray = array();
$arraySize = sizeof($reverseArray);
for($i<arraySize; $i=0; $i--){
echo $reverseArray($i);
}
?>
<?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)
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With