30 Days of Code - Day 7: Arrays
Task
Given an array, A
, of N
integers, print A
's elements in reverse order as a single line of space-separated numbers.
Example
A = [1,2,3,4]
Print 4 3 2 1
. Each integer is separated by one space.
Solution in PHP:
You can print the elements of the array in reverse order by using a loop to iterate through the array in reverse and print each element separated by a space. Here's the code to do that:
<?php
$n = intval(trim(fgets(STDIN)));
$arr_temp = rtrim(fgets(STDIN));
$arr = array_map('intval', preg_split('/ /', $arr_temp, -1, PREG_SPLIT_NO_EMPTY));for ($i = $n - 1; $i >= 0; $i--) {
echo $arr[$i];
if ($i > 0) {
echo ' ';
}
}
This code will iterate through the array in reverse order and print each element followed by a space, except for the last element, which will not have a space after it.