PUBLISHED ON: AUGUST 6, 2021
How to reverse the order of an array in PHP
Answer: Using array_reverse()
function
We can reverse the order of the values in an array using the array_reverse()
function. This is a built-in PHP function that takes an array as its input and returns a new array having the reverse ordered elements.
This function arranges all the elements of an array in just the opposite order of the given array.
Example: Reverse the values of an array
In the given example, we have reversed the values of an array named $array using the PHP built-in function array_reverse()
.
<!DOCTYPE html>
<html>
<head>
<title>Reverse the order of an array in PHP</title>
</head>
<body>
<?php
$array = array("HTML", "CSS", "JavaScript", "PHP", "jQuery");
$new_array = array_reverse($array);
print_r($new_array);
?>
</body>
</html>
Array ( [0] => jQuery [1] => PHP [2] => JavaScript [3] => CSS [4] => HTML )
Using for
loop
We can also reverse the order of the values of the input array using for loop. We just have to specify some conditions within the for loop and then print the values of an array using echo.
Example: Reverse the values of an array using for loop
In the given example, we have reversed the values of the given array name $array using the for
loop.
<!DOCTYPE html>
<html>
<head>
<title>Reverse the order of an array in PHP</title>
</head>
<body>
<?php
$array = array("HTML", "CSS", "JavaScript", "PHP", "jQuery");
$size = sizeof($array);
for($i=$size-1; $i>=0; $i--){
echo $array[$i];
echo "<br>";
}
?>
</body>
</html>
jQuery
PHP
JavaScript
CSS
HTML
Conclusion
In this lesson, we have learned how to reverse the elements of an array in PHP. Here, we have discussed two methods with the help of which we can reverse the order of the element. The first method is using the array_reverse()
function. This is a pre-defined PHP function that enables us to reverse the values of an array. Then we have used the for
loop to reverse the order of the values of an array.