PHP Tutorial

PHP Examples

PHP Practice

PHP Array rsort() Function (With Examples)

In this tutorial, we will learn about the PHP rsort() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP rsort() function

The rsort() function is used to sort an indexed array in descending order.

If array elements are numeric, it sorts based on the numbers, if array elements are the string, it sorts based on the alphabets and if the array contains numeric values and text/strings, it sorts elements based on the alphabets.

It does not return a sorted array, it sorts the input array.

Syntax

The syntax of the rsort() function:

rsort(array, [mode]);

Parameters

The parameters of the rsort() function:

  • array is an input array
  • mode is an optional parameter, its default value is 0, it has following values:
    • 0 - It is used to compare items normally
    • 1 - It is used to compare items numerically
    • 2 - It is used to compare items as strings
    • 3 - It is used to compare items as current locale strings
    • 4 - It is used to compare items as strings (natural ordering)

Return Value

The return type of this method is true, it always returns true.

Sample Input/Output

Input:
$arr1 = array(105, 108, 101, 100, 90);

Output:
arr1 (sorted)...
Array
(    
    [0] => 108  
    [1] => 105  
    [2] => 101  
    [3] => 100  
    [4] => 90   
)

PHP rsort() Function Example

<?php    
$arr1 = array(105, 108, 101, 100, 90);
$arr2 = array("Amit", "Prem", "Prerana", "Aleesha", "Abhishek");

rsort($arr1);
print ("arr1 (sorted)...\n");
print_r ($arr1);

rsort($arr2);
print ("arr2 (sorted)...\n");
print_r ($arr2);    
?>

Output

The output of the above example is:

arr1 (sorted)...
Array
(    
    [0] => 108  
    [1] => 105  
    [2] => 101  
    [3] => 100  
    [4] => 90   
)    
arr2 (sorted)...
Array
(    
    [0] => Prerana 
    [1] => Prem 
    [2] => Amit 
    [3] => Aleesha 
    [4] => Abhishek
)

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.