Sort php multidimensional array by sub-value in PHP

PHPServer Side ProgrammingProgramming

The ‘usort’ function can be used to sort multidimensional arrays in PHP. It sorts an array based on a user-defined criteria −

Example

 Live Demo

<?php
function my_sort($a,$b) {
   if ($a==$b) return 0;
   return ($a<$b)?-1:1;
}
$a=array(4,2,81,63);
usort($a,"my_sort");
$arrlength=count($a);
for($x=0;$x<$arrlength;$x++) {
   echo $a[$x];
   echo "<br>";
}
?>

Output

This will produce the following output −

2
4
63
81

An array with 4 elements is declared and this array is passed to the usort function, as well as calling the user-defined ‘my_sort’ function on the elements to make sure that the sorting takes place is ascending order.

raja
Published on 09-Apr-2020 11:42:47
Advertisements