PHP ksort() Function

PHP ksort() function is “used to sort an array in ascending order based on its keys while maintaining the key-value relationships.”

Syntax

ksort($array, sorttype)

Parameters

$array(required): It is an input array.

$sorttype(optional): There are 6 different sorting types which are discussed below

  1.  SORT_REGULAR(Default) – Compare elements normally without changing types
  2.  SORT_NUMERIC – Compare elements numerically.
  3.  SORT_STRING – Compare elements as strings.
  4.  SORT_LOCALE_STRING – Compare elements as strings based on the current locale.
  5.  SORT_NATURAL – Compare elements as strings using natural ordering.

Return value

 It returns true(PHP 8.2.0), previously it returned bool.

Visual RepresentationVisual Representation of PHP ksort

Example 1:How to Use ksort() Function

<?php

$stcast = [
 'Millie' => 15, 
 'Finn' => 16,
 'Noah' => 15,
 'Gaten' => 16,
 'Caleb' => 17
];
echo 'Before ksort'. "\n";
print_r($stcast);

ksort($stcast);
echo 'After ksort'. "\n";
print_r($stcast);

Output

Before ksort
Array
(
 [Millie] => 15
 [Finn] => 16
 [Noah] => 15
 [Gaten] => 16
 [Caleb] => 17
)
After ksort
Array
(
 [Caleb] => 17
 [Finn] => 16
 [Gaten] => 16
 [Millie] => 15
 [Noah] => 15
)

In the above example, ksort() function has sorted the keys alphabetically: ‘Caleb’ comes before ‘Finn’, followed by ‘Gaten’, ‘Millie’, and ‘Noah’. The corresponding values are preserved with their respective keys.

Example 2: Sorting the associative array by a specific key

<?php

$stcast = array(
  array('name' => 'Millie', 'age' => 15),
  array('name' => 'Finn', 'age' => 16),
  array('name' => 'Caleb', 'age' => 17),
  array('name' => 'Gaten', 'age' => 16),
  array('name' => 'Noah', 'age' => 15),
);

function sortByName($a, $b)
{
  $a = $a['name'];
  $b = $b['name'];

  if ($a == $b) return 0;
    return ($a < $b) ? -1 : 1;
}

function sortByAge($a, $b)
{
   $a = $a['age'];
   $b = $b['age'];

   if ($a == $b) return 0;
     return ($a < $b) ? -1 : 1;
}

echo 'Sort by Name';
usort($stcast, 'sortByName');
print_r($stcast);
echo 'Sort by Age';
usort($stcast, 'sortByAge');
print_r($stcast);

Output

Sort by NameArray
(
 [0] => Array
 (
   [name] => Caleb
   [age] => 17
 )

 [1] => Array
 (
   [name] => Finn
   [age] => 16
 )

 [2] => Array
 (
   [name] => Gaten
   [age] => 16
 )

 [3] => Array
 (
   [name] => Millie
   [age] => 15
 )

 [4] => Array
 (
   [name] => Noah
   [age] => 15
 )

)
Sort by AgeArray
(
 [0] => Array
 (
   [name] => Millie
   [age] => 15
 )

 [1] => Array
 (
   [name] => Noah
   [age] => 15
 )

 [2] => Array
 (
   [name] => Gaten
   [age] => 16
 )

 [3] => Array
 (
   [name] => Finn
   [age] => 16
 )

 [4] => Array
 (
   [name] => Caleb
   [age] => 17
 )

)

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.