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

Hàm rsort() trong PHP

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

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

The rsort() function sorts the values of the indexed array in descending order.

The following table summarizes the technical details of this function.

Return Value: Returns TRUE on success or FALSE on failure.
Version: PHP 4+

Syntax

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

rsort(array, sort_flags);

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

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

// Sorting the fruits array alphabetically in descending order
rsort($fruits);
print_r($fruits);
?>

Tip: The counterpart of the rsort() function is the sort() function, which is used for sorting the values of the indexed array alphabetically or numerically in ascending order.


Parameters

The rsort() function accepts the following parameters.

Parameter Description
array Required. Specifies the array to sort.
sort_flags

Optional. Specifies how array items should be compared. Possible values are:

  • SORT_REGULAR – Compare items normally (don't change types). Default value.
  • SORT_NUMERIC – Compare items numerically.
  • SORT_STRING – Compare items as strings.
  • SORT_LOCALE_STRING – Compare items as strings, based on the current locale.
  • SORT_NATURAL – Compare items as strings using natural ordering.
  • SORT_FLAG_CASE – Can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively.

More Examples

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

The following example sorts an indexed array having numeric values in descending order:

<?php
// Sample array
$numbers = array(2, 5, 10, 8, 15, 13, 20);

// Sorting the numbers array numerically in descending order
rsort($numbers);
print_r($numbers);
?>

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

Bài viết mới

Advertisements