Sort array based on the number of elements in the secondary array set as the value in PHP

StackOverflow https://stackoverflow.com/questions/21199927

  •  29-09-2022
  •  | 
  •  

Question

I gave an array populated to look like this -

$array = array(
   0 => array(2,3,4),
   1 => array(2,3,7,6,8),
   -- and so on  
 );

Is there a shorthand in PHP/PHP5.x to accomplish sorting of such an array based on the number of elements in the value to each key of the primary array? Thanks.

Was it helpful?

Solution

Use usort()

function cmp($a, $b) {
    if (count($a) == count($b)) {
        return 0;
    }
    return (count($a) < count($b)) ? -1 : 1;
}

usort($array, "cmp");

Here's a better optimized version of that function (only calling count() twice):

function cmp($a, $b) {
    $numA = count($a);
    $numB = count($b)
    if ($numA == $numB) {
        return 0;
    }
    return ($numA < $numB) ? -1 : 1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top