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
<!DOCTYPE html>
<html>
<body>
<?php
$array = ["apple", 10, "banana", 2, "cherry", 20];
sort($array); // Sorts the array in ascending order
print_r($array);
?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.