How to change an array in php WITHOUT using the inverse array method

I want to know how to change an array without using the array_reverse method. I have an inverse array that I want to modify. My code is below. can someone point out what I'm doing wrong, as I cannot find any example of reversing an array this way elsewhere. 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); } ?> 
+10
arrays php reverse
source share
5 answers
 <?php $array = array(1, 2, 3, 4); $size = sizeof($array); for($i=$size-1; $i>=0; $i--){ echo $array[$i]; } ?> 
+12
source share

Below is the code to access the array. The goal here is to provide the best solution. Compared to the solution approved above, my decision is repeated only half the length. although this is O (N) times. This can make the solution a little faster when working 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) ?> 
+1
source share

The problem with your method is that when you reach 0, it starts again and index gets the value -1 .

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

How to flip an array without using any predefined functions in PHP .. I had a solution to this problem ... here is my solution ........

 <?php // normal array -------- $myarray = [1,2,3,4,5,6,7,8,9]; //---------------- $arr = []; for($i=9; $i > -1; $i--){ if(!$i==0){ $arr[]= $i; } } print_r($arr); //the out put is [9,8,7,6,5,4,3,2,1]; ?> 
0
source share

Here is another way in which I borrow the code from here and update it so that I eliminate the need to use the $ Temp variable and instead use the destructuring array as follows:

 <?php /* Function to reverse $arr from start to end*/ function reverseArray(&$arr, $start, $end) { while ($start < $end) { [$arr[$start],$arr[$end]] = [$arr[$end],$arr[$start]]; $start++; $end--; } } $a = [1,2,3,4]; reverseArray($a,0,count($a)-1); print_r($a); 

See live code

One of the advantages of this method is that the $ a array is inverted in place, so there is no need to create a new array.

0
source share

All Articles