Home >Backend Development >PHP Tutorial >Reverse an array using PHP's array_reverse() function

Reverse an array using PHP's array_reverse() function

WBOY
WBOYOriginal
2023-11-04 11:50:001148browse

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:

<?php
// 定义一个数组
$numbers = array(1, 2, 3, 4, 5);

// 使用array_reverse()函数反转数组
$reversedNumbers = array_reverse($numbers);

// 输出反转后的数组
print_r($reversedNumbers);
?>

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
)

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:

<?php
// 定义一个关联数组
$fruits = array(
    'apple' => '苹果',
    'banana' => '香蕉',
    'orange' => '橙子'
);

// 使用array_reverse()函数反转关联数组
$reversedFruits = array_reverse($fruits);

// 输出反转后的关联数组
print_r($reversedFruits);
?>

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

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

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!

Statement:
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