Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array by boolean values

I have an array that looks something like this:

array(
  array('foo' => true),
  array('foo' => false),
  array('foo' => true),
  array('foo' => true),
  array('foo' => false)
)

Is there a simple way to bring all the arrays where foo == true to the top?

like image 719
Jason Varga Avatar asked Sep 03 '25 17:09

Jason Varga


1 Answers

Just use the uasort() function to order your array:

$arr = array(
    array('foo' => true),
    array('foo' => false),
    array('foo' => true),
    array('foo' => true),
    array('foo' => false)
);

function sortit($a, $b) {
    if($a['foo'] === $b['foo']) {
        return 0;
    }

    return $a['foo'] > $b['foo'] ? -1 : 1;
}

uasort($arr, 'sortit');
like image 183
jterry Avatar answered Sep 07 '25 07:09

jterry