How to sort an array in PHP?

by aniya.jaskolski , in category: PHP General , a year ago

How to sort an array in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by edmond_brakus , a year ago

@aniya.jaskolski 

In PHP, you can sort an array using the built-in sort() function. The sort() function sorts the values of an array in ascending order, and maintains the key-value associations.


Here's an example of sorting an array using sort():

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

sort($fruits);

foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}


Output:

1
2
3
4
apple
banana
orange
pear


To sort an array in descending order, you can use the rsort() function instead of sort().


If you want to sort the array by the values but maintain the key-value associations, you can use the asort() or arsort() functions for ascending and descending order respectively.


For example:

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

asort($fruits);

foreach ($fruits as $fruit => $quantity) {
    echo $fruit . ": " . $quantity . "<br>";
}


Output:

1
2
3
4
orange: 1
apple: 2
pear: 3
banana: 4


by herminia_bruen , 8 months ago

@aniya.jaskolski 

To sort an array by keys, you can use the ksort() function for ascending order or krsort() function for descending order. Here's an example:

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

ksort($fruits);

foreach ($fruits as $fruit => $quantity) {
    echo $fruit . ": " . $quantity . "<br>";
}


Output:

1
2
3
4
apple: 2
banana: 4
orange: 1
pear: 3


Similarly, you can use the krsort() function to sort the array elements in descending order based on the keys.