OneBite.Dev - Coding blog in a bite size

Reverse Arrays Items In PHP

Code snippet for how to Reverse Arrays Items In PHP with sample and detail explanation

In this article, we will delve into the method used in PHP to reverse order of elements in an array. This is not only a frequently used operation, but also a basic one that underlies many complex operations.

Code snippet: Reversing Array Items in PHP

Below is a short piece of code illustrating how to reverse items in a PHP array:

<?php
    $originalArray = array("First Item", "Second Item", "Third Item", "Fourth Item");
    $reversedArray = array_reverse($originalArray);

    print_r($reversedArray);
?>

When we run this code, we receive the following output:

Array
(
    [0] => Fourth Item
    [1] => Third Item
    [2] => Second Item
    [3] => First Item
)

As you can see, the original array items have indeed been reversed.

Code Explanation for Reversing Array Items in PHP

Let’s explain how the code provided above works step by step.

  1. Firstly, we are creating an array named $originalArray containing four items. You can populate your array with as many or as few data as you wish.
$originalArray = array("First Item", "Second Item", "Third Item", "Fourth Item");
  1. Next, we are utilizing the array_reverse() function in PHP. In a nutshell, array_reverse() accepts any array as its input and outputs the same array with its elements in reverse order. We are storing the output array in a new variable called $reversedArray.
$reversedArray = array_reverse($originalArray);
  1. Lastly, we use the print_r() function, which is a built-in PHP function used to print human-readable information about a variable. In this case, we are printing out the $reversedArray variable:
print_r($reversedArray);

To summarize, the array_reverse() function in PHP serves a valuable purpose, enabling you to reverse the order of elements in an array in a straightforward and efficient manner. Implementing it, as evidenced from the tutorial above, is both simple and quick.

php