PHP Array ksort() Function (With Examples)

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

PHP ksort() function

The ksort() function is used to sort an associative array in ascending 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 ksort() function:

ksort(array, [mode]);

Parameters

The parameters of the ksort() 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
(    
    [abhi] => 20 
    [amit] => 21 
    [manju] => 25
    [prem] => 27 
    [radib] => 21
)

PHP ksort() Function Example

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

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

ksort($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
(    
    [abhi] => 20 
    [amit] => 21 
    [manju] => 25
    [prem] => 27 
    [radib] => 21
)

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.