PHP Program to print the elements of array in reverse order

What is meant by the reverse of the array?

In this program, we are printing the array in the reverse order which means we are printing the last element at first and so on. For example, if the original order of the array is 1, 2, 3, 4, 5 then the reverse of the array will be 5, 4, 3, 2, 1.

How to print the elements of the array in reverse order?

To print the array in reverse order first we have to assign the values into the array a[]. After that, we have to assign the size of the array to the variable size using the built-in function count() and then print the elements in the original array using for loop. Then we have to use for loop itself to print the array in reverse order for that first we have to assign the computed value of 'size - 1' to the variable i and print the elements of the array a[i] and perform this printing until the condition 'i >= 0' becomes false and also decrement the value of by 1 in every iteration.

ALGORITHM

Step 1: Initialize an array a[] with values

Step 2: Assing the size of the array into the variable size using the built-in function count()

Step 3: Print the elements of the array a[] using for loop

Step 4: To print the array in reverse order using for loop fir assign value 'size - 1' into the variable i and perform the sub-step until the condition 'i >= 0' becomes false and decrement the size of by 1 in every iteration

        (i) Print the element of array a[i]

PHP Source Code

                                          <?php
$a = array(1, 2, 3, 4, 5);
echo "Array in original order: \n";
$size = count($a);
for ($i = 0; $i < $size; $i++) {
    echo "$a[$i] ";
}
echo "\nArray in reverse order: \n";
for ($i = $size - 1; $i >= 0; $i--) {
    echo "$a[$i] ";
}
?>
                                      

OUTPUT

Array in original order:
1 2 3 4 5
Array in reverse order:
5 4 3 2 1