How to Reverse an Array in PHP: Simple Guide for Beginners

When we say “reverse an array,” it means we want the last element to come first, and the first element to go last.

For example, if we have:

<?php
$array = ["HTML", "CSS", "JavaScript", "PHP", "jQuery"];

?>

The reversed version will be:

<?php
["jQuery", "PHP", "JavaScript", "CSS", "HTML"]

?>

Using array_reverse() function

PHP provides a built-in function called array_reverse() to reverse arrays easily.

Syntax:

<?php
array_reverse(array, preserve);

?>

array → The array you want to reverse (required)

preserve → true/false (optional). If true, the original keys are kept; if false, new numeric keys are assigned.

Example


<?php
$array = ["HTML", "CSS", "JavaScript", "PHP", "jQuery"];
$new_array = array_reverse($array);
print_r($new_array);
?>

Output

<?php
Array ( [0] => jQuery [1] => PHP [2] => JavaScript [3] => CSS [4] => HTML )

?>

Explanation:
array_reverse() automatically flips the array, so the last element comes first.

Using a for loop

You can also reverse an array manually using a for loop.

Idea:

  • Start from the last element of the array.
  • Go backwards until the first element.
  • Print each element.

Example

<?php
$array = ["HTML", "CSS", "JavaScript", "PHP", "jQuery"];
$size = sizeof($array); // find total elements

for($i = $size - 1; $i >= 0; $i--){
    echo $array[$i];
    echo "<br>";
}
?>

output

jQuery
PHP
JavaScript
CSS
HTML

Explanation:

  • $size - 1 → last index of the array.
  • $i >= 0 → go till the first element.
  • $i-- → decrease index in each step to go backward.

Summary:

MethodEasy to UseKeys Preserved?Notes
array_reverse()EasyOptionalBest for simple reversing
for loopEasyOriginal keys stay if you print manuallyGood to learn logic manually