PHP ksort: How to sort array by key in PHP

0
26
PHP ksort Function Example | How To Sort Array By Key in PHP

Key-value associations become essential when you are dealing with associative arrays. The ksort() function is useful mainly for associative arrays.

One of PHP’s most robust data types is an array. It can hold numbers and contain characters; it can be sliced, sorted, and chunked. The specific sorting functions are only for sorting by the keys or values when sorting the array.

PHP ksort

PHP ksort() is a built-in function that sorts the associative array in ascending order, according to the key. It sorts an array by key, maintaining the key to data correlations.

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 straightforward 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.

Syntax

See the following syntax.

ksort(array, sorttype)

Parameters

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

The sorttype is optional and specifies how to compare the array of 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 the 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

Do 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 comprises arrays that hold the cast’s name and 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 value in numerical, alphabetical, descending, and ascending order in PHP.

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

That’s it for this tutorial.

Recommended Posts

PHP sort

PHP unset

PHP array_sum

PHP in_array

PHP json_decode

Leave A Reply

Please enter your comment!
Please enter your name here

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