How to sort array by key in PHP?

by raven_corwin , in category: PHP General , 2 years ago

How to sort array by key in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by brandy , 2 years ago

@raven_corwin 

To sort an array by key in PHP, you can use the ksort() function. This function sorts an associative array in ascending order, according to the key.

Here's an example of how you can use ksort() to sort an array by key:

1
2
3
4
5
6
7
8
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

ksort($fruits);

foreach ($fruits as $key => $val) {
    echo "$key = $val
";
}

In this example, the $fruits array is sorted in ascending order by key, and the resulting array is:

1
2
3
4
a = orange
b = banana
c = apple
d = lemon

You can also sort an array in descending order by key by using the krsort() function instead of ksort(). The krsort() function sorts an associative array in descending order according to the key.

Here's an example of how you can use krsort() to sort an array in descending order by key:

1
2
3
4
5
6
7
8
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

krsort($fruits);

foreach ($fruits as $key => $val) {
    echo "$key = $val
";
}

In this example, the $fruits array is sorted in descending order by key, and the resulting array is:

1
2
3
4
d = lemon
c = apple
b = banana
a = orange

I hope this helps! Let me know if you have any other questions.

Member

by gilbert , a year ago

@raven_corwin 

You can sort an array by its keys in PHP using the ksort() function. The ksort() function sorts an associative array in ascending order based on the keys. Here's an example:

1
2
3
4
5
6
7
$fruits = array("banana" => 2, "apple" => 5, "orange" => 3);
ksort($fruits);

foreach ($fruits as $key => $value) {
    echo $key . " = " . $value . "
";
}


Output:

1
2
3
apple = 5
banana = 2
orange = 3


In the example above, the ksort() function is used to sort the $fruits array by its keys. The foreach loop is then used to iterate through the sorted array and display the key-value pairs.