usort() sorts values with a callback and reindexes numeric keys. In current PHP, the spaceship operator makes many comparison callbacks concise.
$products = [
['name' => 'Book', 'price' => 250],
['name' => 'Pen', 'price' => 40],
['name' => 'Bag', 'price' => 900],
];
usort($products, fn($a, $b) => $a['price'] <=> $b['price']);
print_r($products);If original keys matter, choose a key-preserving sorting approach instead of usort().
<?Php
function compare($x,$y){
$x=strlen($x);
$y=strlen($y);
if($x==$y){
return 0;
}
return ($x < $y) ? -1 : 1;
}
$input = array ("Pineapple", "Orange", "Banana", "Mango", "Apple","Strawberry","aaa","bb");
foreach ($input as $key => $val) {
echo "$key -> $val <br>";
}
usort($input, "compare");
echo "<br>-----After usort---------<br>";
foreach ($input as $key => $val) {
echo "$key -> $val <br>";
}
?>
Here is the output of usort function where user defined comparisons function is used
0 -> Pineapple
1 -> Orange
2 -> Banana
3 -> Mango
4 -> Apple
5 -> Strawberry
6 -> aaa
7 -> bb
-----After usort---------
0 -> bb
1 -> aaa
2 -> Apple
3 -> Mango
4 -> Orange
5 -> Banana
6 -> Pineapple
7 -> Strawberry
$array = [
['name' => 'John', 'age' => 25],
['name' => 'Anna', 'age' => 22],
['name' => 'Mike', 'age' => 30]
];
usort($array, function($a, $b) {
return $a['age'] - $b['age'];
});
print_r($array);
output
Array ( [0] => Array ( [name] => Anna [age] => 22 ) [1] => Array ( [name] => John [age] => 25 ) [2] => Array ( [name] => Mike [age] => 30 ) )
$array = ['Banana', 'apple', 'Cherry'];
usort($array, 'strcasecmp');
print_r($array);
Array ( [0] => apple [1] => Banana [2] => Cherry )
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.