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);
?>
Explanation:
- Function Definition:
- A function named test is defined with one parameter:
- $nums: an array of numbers.
- Array Reversal:
- The function returns a new array that contains the elements of $nums in reverse order:
- It explicitly selects elements in the order of index 4, 3, 2, 1, and 0, effectively reversing the array.
- Array Initialization:
- An array $a is created with the initial values: [10, 20, -30, -40, 50].
- Display Original Array:
- The original array is displayed using echo and implode to format the array as a string:
- Function Call:
- The test function is called with the array $a, and the result is stored in the variable $result.
- Display Reversed Array:
- The reversed array is displayed using echo and implode to format the reversed array as a string:
Output:
Original array: 10,20,-30,-40,50 Reverse array: 50,-40,-30,20,10
Flowchart:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-91.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics