w3resource

PHP Exercises: Reverse a given array of integers and length 5

PHP Basic Algorithm: Exercise-91 with Solution

Write a PHP program to reverse a given array of integers and length 5.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that reverses the order of elements in the given array.
function test($nums)
{ 
    // Return a new array with elements in reverse order.
    return [$nums[4], $nums[3], $nums[2], $nums[1], $nums[0]];
}

// Create an array $a with initial values.
$a = [10, 20, -30, -40, 50];

// Display the original array.
echo "Original array: " . implode(',', $a) . "\n";

// Call the 'test' function to reverse the array elements.
$result = test($a);

// Display the reversed array.
echo "Reverse array: " . implode(',', $result);
?>

Sample Output:

Original array: 10,20,-30,-40,50
Reverse array: 50,-40,-30,20,10

Flowchart:

Flowchart: Reverse a given array of integers and length 5.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to rotate the elements of a given array of integers (length 4 ) in left direction and return the new array.
Next: Write a PHP program to find out the maximum element between the first or last element in a given array of integers ( length 4), replace all elements with maximum element.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.