How to sort an array in PHP?

by aniya.jaskolski , in category: PHP General , 6 months ago

How to sort an array in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 6 months 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