Dev Diaries WD logo Dev Diaries WD
PHP INTERVIEW · EP 05
PHP INTERVIEW · Episode 05

PHP sorting: sort() vs asort() vs ksort()

Which one keeps your keys, and which sorts by them?

ep5_array_sorting.php
<?php
$scores = [
    "Rahul"  => 85,
    "Anshul" => 72,
    "Manish" => 90,
    "Vikash" => 65,
];

$normalSort = $aSort = $kSort =  $scores;

sort($normalSort);
asort($aSort);
ksort($kSort);
Output

Normal sort by sort() function

Array
(
    [0] => 65
    [1] => 72
    [2] => 85
    [3] => 90
)

       

A sort by asort() function

Array
(
    [Vikash] => 65
    [Anshul] => 72
    [Rahul] => 85
    [Manish] => 90
)

        

K sort by ksort() function

Array
(
    [Anshul] => 72
    [Manish] => 90
    [Rahul] => 85
    [Vikash] => 65
)

      

Watch the full episode

Watch on YouTube