Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort php multidimensional array by sub-value in PHP
The ‘usort’ function can be used to sort multidimensional arrays in PHP. It sorts an array based on a user-defined criteria −
Example
<?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.
Advertisements