- PHP

How to sort the Array by Key in PHP

Use the ksort() function.

ksort($array);

Example:

In the array, we have keys (names) with some values, such as age or favorite color. Let’s sort this information alphabetically by each user’s name.

<?php

$people = [
    "Zack" => ['age' => 32, 'favoriteColor' => 'red'],
    "Adam" => ['age' => 24, 'favoriteColor' => 'blue'],
    "Kate" => ['age' => 28, 'favoriteColor' => 'pink'],
    "Michele" => ['age' => 38, 'favoriteColor' => 'brown'],
    "Peter" => ['age' => 29, 'favoriteColor' => 'purple'],
    "Thomas" => ['age' => 47, 'favoriteColor' => 'green'],
    "Betty" => ['age' => 32, 'favoriteColor' => 'white'],
];

ksort($people);

print_r($people);

Output:


Array
(
    [Adam] => Array
        (
            [age] => 24
            [favoriteColor] => blue
        )

    [Betty] => Array
        (
            [age] => 32
            [favoriteColor] => white
        )

    [Kate] => Array
        (
            [age] => 28
            [favoriteColor] => pink
        )

    [Michele] => Array
        (
            [age] => 38
            [favoriteColor] => brown
        )

    [Peter] => Array
        (
            [age] => 29
            [favoriteColor] => purple
        )

    [Thomas] => Array
        (
            [age] => 47
            [favoriteColor] => green
        )

    [Zack] => Array
        (
            [age] => 32
            [favoriteColor] => red
        )

)