Skip to content
Advertisement

Sorting an array of arrays by the child array’s length?

What’s the best way in PHP to sort an array of arrays based on array length?

e.g.

$parent[0] = array(0, 0, 0);
$parent[2] = array("foo", "bar", "b", "a", "z");
$parent[1] = array(4, 2);

$sorted = sort_by_length($parent)

$sorted[0] = array(4, 2);
$sorted[1] = array(0, 0, 0);
$sorted[2] = array("foo", "bar", "b", "a", "z");

Advertisement

Answer

This will work:

function sort_by_length($arrays) {
    $lengths = array_map('count', $arrays);
    asort($lengths);
    $return = array();
    foreach(array_keys($lengths) as $k)
        $return[$k] = $arrays[$k];
    return $return;
}

Note that this function will preserve the numerical keys. If you want to reset the keys, wrap it in a call to array_values().

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement