Hướng dẫn
Quảng cáo

Hàm array_reverse() trong PHP

Hướng dẫn cách sử dụng hàm array_reverse() về mảng trong lập trình PHP

Tác dụng của hàm array_reverse()

The array_reverse() function reverses the order of the elements in an array.

The following table summarizes the technical details of this function.

Return Value: Returns the reversed array.
Version: PHP 4+

Syntax

The basic syntax of the array_reverse() function is given with:

array_reverse(array, preserve);

The following example shows the array_reverse() function in action.

<?php
// Sample array
$fruits = array("apple", "banana", "orange", "mango");

// Reversing the order of the array
print_r(array_reverse($fruits));
?>

Parameters

The array_reverse() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to work on.
preserve Optional. Specifies whether numeric keys should be preserved or not. Possible values are true and false. Non-numeric keys will always be preserved.

More Examples

Here're some more examples showing how array_reverse() function actually works:

The following example shows how to reverse the order of array elements while preserving the keys.

<?php
// Sample array
$input = array("dog", "zebra", array("cat", "tiger"));

// Reversing the order of the array
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);

// Printing arrays
print_r($input);
print_r($reversed);
print_r($preserved);
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements