I have an array of the form
$a = array(
'a' => 0,
'b' => 0,
'c' => 1
);
and want an array of the form
array(
0 => array('a','b'),
1 => array('c')
);
What is the most efficient way to do this?
This can be achieved with a body-less loop because values are processed before keys in the signature of foreach() loop. Define the $v variable, then use that variable as the first level key as you push the original key as a new child element in the result array. This approach uses one less variable declaration versus the classic "bodied" loop.
Code: (Demo)
$result = [];
foreach ($a as $result[$v][] => $v);
var_export($result);
See also: Within a foreach() expression, is the value defined before or after the key?
Functional iteration is decidedly less elegant: (Demo)
var_export(
array_reduce(
array_keys($a),
function ($result, $k) use ($a) {
$result[$a[$k]][] = $k;
return $result;
}
)
);