Using PHP’s array_reverse Function to Reverse Array Elements
This tutorial explains how the PHP array_reverse function works, details its parameters, and provides clear code examples showing how to reverse an array’s order and optionally preserve its keys.
PHP is a powerful scripting language that can be used not only for web development but also for handling arrays. This article introduces how to use the PHP function array_reverse to reverse the order of array elements.
First, we review the usage of array_reverse . The function reverses the order of the elements in an array and returns the result. Its syntax is:
array array_reverse ( array $array [, bool $preserve_keys = FALSE ] )Parameter description:
$array : the array to be processed.
$preserve_keys : by default the reversed array reindexes its keys; set to TRUE to keep the original keys.
Below is a code example that demonstrates how to use array_reverse to reverse an array.
<?php
// Create a simple array
$fruits = array("apple", "banana", "orange", "grape");
// Output the original array
echo "Original array: ";
print_r($fruits);
// Reverse the array
$reversed_fruits = array_reverse($fruits);
// Output the reversed array
echo "Reversed array: ";
print_r($reversed_fruits);
?>In the code, we first create the $fruits array containing several fruit names. Then we call array_reverse to reverse the array and store the result in $reversed_fruits . Finally, we print both the original and the reversed arrays.
Running the script produces the following output:
Original array: Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => grape
)
Reversed array: Array
(
[0] => grape
[1] => orange
[2] => banana
[3] => apple
)The output shows that array_reverse successfully reversed the element order.
If you need to preserve the original keys, pass TRUE as the second argument:
$reversed_fruits = array_reverse($fruits, true);This tutorial demonstrates how to use PHP’s array_reverse function to reverse arrays, whether they are simple indexed arrays or associative arrays, and how to keep keys when needed.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.