phparraysarray-flip

array_flip of a key value for letter and numbers


I have an array like this

array(123=>'c', 125=>'b', 139=>'a', 124=>'c', 135=>'c', 159=>'b');

and I want to flip the key/values so that duplicate values become an index for an array.

array(
    'a'=>array(139),
    'b'=>array(125, 159),
    'c'=>array(123, 124, 135)
);

However, array_flip seems to overwrite the keys and array_chunk only splits it based on number values.

Any suggestions?


Solution

  • function array_flop($array) {
        foreach($array as $k => $v) {
            $result[$v][] = $k;
        }
        return array_reverse($result);
    }