Reverse an array using PHP's array_reverse() function

WBOY
Release: 2023-11-04 11:52:01
Original
964 people have browsed it

Reverse an array using PHPs array_reverse() function

Use PHP's array_reverse() function to reverse an array

In PHP, you can use the array_reverse() function to reverse the order of the elements of an array. This function accepts an array as a parameter and returns a new array whose elements are the reverse order of the elements in the original array.

The following is a specific example code using the array_reverse() function:

Copy after login

In the above code, we first define an array named $numbers, which contains some integers. We then reverse the $numbers array using the array_reverse() function and store the result in a new array called $reversedNumbers. Finally, we use the print_r() function to print out the $reversedNumbers array.

Run the above code and you will get the following output:

Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )
Copy after login

You can see that the output result is a new array in which the elements in the original array $numbers are arranged in reverse order.

The array_reverse() function can be used not only for ordinary index arrays, but also for associative arrays. The following is a sample code that uses the array_reverse() function to reverse an associative array:

 '苹果', 'banana' => '香蕉', 'orange' => '橙子' ); // 使用array_reverse()函数反转关联数组 $reversedFruits = array_reverse($fruits); // 输出反转后的关联数组 print_r($reversedFruits); ?>
Copy after login

Run the above code, you will get the following output:

Array ( [orange] => 橙子 [banana] => 香蕉 [apple] => 苹果 )
Copy after login

You can see that the output result is the original associative array A new array of key-value pairs in $fruits sorted in reverse order.

Summary: Use PHP's array_reverse() function to conveniently reverse the order of elements in an array. Whether it is an indexed array or an associative array, the array_reverse() function can handle it correctly. Simply pass the array to be reversed as a parameter to the array_reverse() function and store the returned result in a new array to achieve the array reversal function.

The above is the detailed content of Reverse an array using PHP's array_reverse() function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!