AppDividend
Latest Code Tutorials

PHP ksort() Function Example | How To Sort Array By Key in PHP

0

PHP ksort Function Example | How To Sort Array By Key in PHP is today’s topic. One of PHP’s most robust data types is an array. It can hold numbers, and it can contain characters, it can be sliced, sorted, and chunked. Speaking of sorting, when sorting the array, the straight forward sorting functions are only for sorting by the keys or by the values. The ksort() function sorts the associative array in ascending order, according to the key. It sorts an array by key, maintaining the key to data correlations. The function is useful mainly for the associative arrays.

PHP ksort Function

Key-value associations become essential when you are dealing with associative arrays. 

We can use the ksort() function for sorting the associative array by key alphabetically in ascending order while maintaining a relationship between the key and data.

For example, you might have an array with info about the total number of airport terminals in various countries.

Assuming that all the names of different countries are the keys and the numbers of the airports are values, you might want to sort all the country names alphabetically.

It is very easy to do with the ksort(), and krsort() functions. Both these functions will maintain a key-value association of the array items after sorting.

A ksort() function sorts the keys from low to high, and the krsort() sorts the keys from high to low.

See the following syntax.

ksort(array, sorttype)

The array parameter is required, and it tells the array to sort.

The sorttype is optional and it specifies how to compare the array elements/items. Possible values:

  1. 0 = SORT_REGULAR – Default. Compare elements normally (don’t change types).
  2. 1 = SORT_NUMERIC – Compare elements numerically.
  3. 2 = SORT_STRING – Compare elements as strings.
  4. 3 = SORT_LOCALE_STRING – Compare elements as strings, based on current locale.
  5. 4 = SORT_NATURAL – Compare elements as strings using natural ordering.

How To Sort Array By Key in PHP

The ksort() and krsort make PHP sort associative arrays, but they don’t do it by the value of an associative array: what matters here is a key. In our example, names were the keys.

Hence, using these two functions will sort the cast name and age.

We can use ksort() for ascending order.

<?php

// app.php

$stcast = [
  'Millie' => 15, 
  'Finn' => 16,
  'Noah' => 15
];
ksort($stcast);
print_r($stcast);

See the output.

➜  pro php app.php
Array
(
    [Finn] => 16
    [Millie] => 15
    [Noah] => 15
)
➜  pro

Sorting the associative array by a specific key with PHP

You have the array of arrays and want to sort by a specific key in the array? That’s where usort() comes in. First, let’s get our array set up:

<?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),
);

The array above is comprised of arrays that hold the name of the cast and their age. It’s mixed up on purpose so that we can sort it.

To use usort(), we either need to create a function or use an anonymous function that’s passed it at run time.

I’m opting to use the separate functions for the examples but will elaborate on how to make an awesome function that’s reusable for any field.

If we want to start, let’s create two functions, 1 to sort by name and one to sort by age.

See the following full program.

<?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);

Okay, now see the output.

➜  pro php app.php
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
        )

)
➜  pro

So this is how you sort the array by key or by value, in numerical, alphabetical, descending, and ascending order in PHP.

Some functions in PHP can only be applied for the associative arrays.

Finally, PHP ksort Function Example | How To Sort Array By Key in PHP is over.

Recommended Posts

PHP sort() Function Example

PHP unset Example

PHP Array Sum Example

PHP in_array Example

PHP json_decode Example

Leave A Reply

Your email address will not be published.

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