3

I'm looking for an elegant way to turn this array:

Array (
  [foo] => 1
  [bar] => 1
  [zim] => 3
  [dib] => 6
  [gir] => 1
  [gaz] => 3
)

Into this array:

Array (
  [1] => Array ( foo, bar, gir ),
  [3] => Array ( zim, gaz ),
  [6] => Array ( dib )
)

Note:, there is no relationship between the keys or values. They are completely arbitrary and used as examples only. The resulting array should be an associative array grouped by the values of the input array.

Thanks!

flag

78% accept rate

2 Answers

9
$input = array(
  'foo' => 1,
  'bar' => 1,
  'zim' => 3,
  'dib' => 6,
  'gir' => 1,
  'gaz' => 3
)

$output = array();
foreach ( $input as $k => $v ) {
  if ( !isset($output[$v]) ) {
    $output[$v] = array();
  }

  $output[$v][] = $k;
}
link|flag
3

I think this will do it just fine:

foreach ($arr1 as $k => $val) $arr2[$val][] = $k;

where $arr1 is the original array outputting the new array to $arr2.

link|flag
I thought this would've generated a PHP warning, but nope! Concise and sweet FTW! – macek Apr 21 at 18:51
this indeed doesn't generate a warning, but relying on a php bug feels quite dirty. hsz's code is cleaner. – stereofrog Apr 21 at 18:57
@stereofrog, can you detail the "bug"? – macek Apr 21 at 19:14
@macek: no warning when using an undefined variable is clearly a bug – stereofrog Apr 21 at 20:12
@stereofrog, I suppose that's a fair argument. You're right, too. I shouldn't sacrifice reliable functionality just for the sake of trimming a line or two out. – macek Apr 21 at 20:44
show 2 more comments

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.