How to reverse an array in PHP

Created
Modified

Using array_reverse Function

The array_reverse() return an array with elements in reverse order.

$arr = array("PHP", 8.1, 4);

$reversed = array_reverse($arr);
print_r($reversed);
$preserved = array_reverse($arr, true);
print_r($preserved);
Array
(
  [0] => 4
  [1] => 8.1
  [2] => PHP
)
Array
(
  [2] => 4
  [1] => 8.1
  [0] => PHP
)

Using Swapping Method

Here is another solution using same variable names as yours and using swapping method.

function Reverse($arr) {
  for ($i=count($arr) - 1, $j = 0; $j < $i ; $i--, $j++) { 
    $temp = $arr[$i];
    $arr[$i] = $arr[$j];
    $arr[$j] = $temp;
  }
  return $arr;
}

// without using any PHP function and any other variable
function Reverse($arr) {
  $count = count($arr);
  for ($i=0; $i < $count/2 ; $i++) { 
    [$arr[$i], $arr[$count-$i-1]] = [$arr[$count-$i-1], $arr[$i]];
  }
  return $arr;
}

$arr = array("PHP", 8.1, 4);

$reversed = Reverse($arr);
print_r($reversed);
Array
(
  [0] => 4
  [1] => 8.1
  [2] => PHP
)

Related Tags