WS WhereIsStuff
Tutorial Guides
Log In
Sign Up

Advertisement

Google Ad Slot: content-top

PHP Sorting Arrays


PHP provides several functions to sort arrays. You can sort arrays by their values or keys, in ascending or descending order, and you can also use custom sorting functions.


Sort Functions For Arrays

Sort function

Description

Example

sort()

Sorts the array in ascending order

$fruits = ["banana", "apple", "cherry", "date"];
sort($fruits); // Sorts in ascending alphabetical order
print_r($fruits);


Try it yourself

rsort()

Sorts Array in Descending Order


$fruits = ["banana", "apple", "cherry", "date"];
rsort($fruits); // Sorts in ascending alphabetical order
print_r($fruits);

Try it yourself

asort()



Sorts the array in ascending order while maintaining the key-value pairs


$ages = ["John" => 30, "Alice" => 25, "Bob" => 35];
asort($ages); // Sorts by value in ascending order
print_r($ages); // Output: ["Alice" => 25, "John" => 30, "Bob" => 35]


Try it yourself

arsort()


Sorts the array in descending order while maintaining the key-value pairs

$ages = ["John" => 30, "Alice" => 25, "Bob" => 35];
arsort($ages); // Sorts by value in descending order
print_r($ages); // Output: ["Bob" => 35, "John" => 30, "Alice" => 25]

Try it yourself

ksort()


Sorts the array by key in ascending order

$ages = ["John" => 30, "Alice" => 25, "Bob" => 35];
ksort($ages); // Sorts by key in ascending order
print_r($ages); // Output: ["Alice" => 25, "Bob" => 35, "John" => 30]


Try it yourself

krsort()

Sorts the array by key in descending order

$ages = ["John" => 30, "Alice" => 25, "Bob" => 35];
krsort($ages); // Sorts by key in ascending order
print_r($ages); // Output: ["Alice" => 25, "Bob" => 35, "John" => 30]


Try it yourself

Sort with both numerical and alphabetical values


When using the sort() function in PHP to sort an array containing both numerical and alphabetical values, it sorts the elements lexicographically (alphabetically by character values).

Example
<?php
$array = ["apple", 10, "banana", 2, "cherry", 20];
sort($array); // Sorts the array in ascending order
print_r($array);
?>
Try it yourself