4

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!

2 Answers 2

12
$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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

I thought this would've generated a PHP warning, but nope! Concise and sweet FTW!
@stereofrog, can you detail the "bug"?
@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.
@stereofrog: I could have sworn I've seen this type of example in the manual pages. Cause if what your saying is true my code is totally fed up.
I never define variables first, what a waste of a line of code. That's why I use PHP, because you don't have too.

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.