PHP Tutorial

PHP Examples

PHP Practice

PHP Array krsort() Function (With Examples)

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

PHP krsort() function

The krsort() function is used to sort an associative array in descending order based on the keys, as we know that an associative array contains keys and values, this method sorts an array according to the keys.

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

Syntax

The syntax of the krsort() function:

krsort(array, [mode]);

Parameters

The parameters of the krsort() 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:
$person = array(
    "radib" => 21,
    "amit" => 21,
    "abhi" => 20,
    "prem" => 27,
    "manju" => 25
    );

Output:
sorted array...  
Array
(    
    [radib] => 21
    [prem] => 27 
    [manju] => 25
    [amit] => 21 
    [abhi] => 20 
) 

PHP krsort() Function Example

<?php
$person = array(
    "radib" => 21,
    "amit" => 21,
    "abhi" => 20,
    "prem" => 27,
    "manju" => 25,
);

print "unsorted array...\n";
print_r($person);
//sorting...

krsort($person);
print "sorted array...\n";
print_r($person);
?>

Output

The output of the above example is:

unsorted array...
Array
(    
    [radib] => 21
    [amit] => 21 
    [abhi] => 20 
    [prem] => 27 
    [manju] => 25
)    
sorted array...  
Array
(    
    [radib] => 21
    [prem] => 27 
    [manju] => 25
    [amit] => 21 
    [abhi] => 20 
)

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.