-2

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?

2 Answers 2

2

I think you'll just have to use a foreach, as array_flip will make you lose the duplicates:

$b = array();
foreach ($a as $k => $v) {
    $b[$v][] = $k;
}

var_dump($b);
Sign up to request clarification or add additional context in comments.

Comments

0

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;
        }
    )
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.