Using PHP array_reverse() to Reverse Indexed and Associative Arrays
This article explains how PHP's array_reverse() function can reverse both indexed and associative arrays, provides clear code examples, shows the resulting output, and includes a brief summary of its usage for developers.
In PHP, you can use array_reverse() function to reverse the order of elements in an array. This function takes an array as a parameter and returns a new array with elements in reverse order.
Below is a concrete example code using array_reverse() function:
<code><?php
// 定义一个数组
$numbers = array(1, 2, 3, 4, 5);
// 使用array_reverse()函数反转数组
$reversedNumbers = array_reverse($numbers);
// 输出反转后的数组
print_r($reversedNumbers);
?>
</code>In the above code, we first define an array named $numbers containing some integers. Then we use array_reverse() to reverse $numbers and store the result in a new array $reversedNumbers . Finally we use print_r() to output $reversedNumbers .
Running the above code will produce the following output:
<code>Array
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)
</code>As you can see, the output is a new array with the elements of the original $numbers in reverse order.
The array_reverse() function can also be used with associative arrays. Below is an example code that reverses an associative array:
<code><?php
// 定义一个关联数组
$fruits = array(
'apple' => '苹果',
'banana' => '香蕉',
'orange' => '橙子'
);
// 使用array_reverse()函数反转关联数组
$reversedFruits = array_reverse($fruits);
// 输出反转后的关联数组
print_r($reversedFruits);
?>
</code>Running the above code will produce the following output:
<code>Array
(
[orange] => 橙子
[banana] => 香蕉
[apple] => 苹果
)
</code>You can see the result is a new array where the key‑value pairs of the original $fruits are reversed.
Summary: Using PHP's array_reverse() function can conveniently reverse the order of elements in an array. Whether it is an indexed array or an associative array, array_reverse() works correctly. Just pass the array to array_reverse() and store the returned result in a new array to achieve reversal.
PHP Learning Recommendations:
Vue3+Laravel8+Uniapp Beginner to Practical Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Master Recommended Course
Workerman+TP6 Real‑time Chat System Limited‑time Offer
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.