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.
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 i by 1 in every iteration.
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 i by 1 in every iteration
(i) Print the element of array a[i]
<?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] ";
}
?>
Array in original order: 1 2 3 4 5 Array in reverse order: 5 4 3 2 1