Voting

: six plus three?
(Example: nine)

The Note You're Voting On

ilanfir at gmail dot com
10 years ago
I recently had to flip an array and group the elements by value, this snippet will do that:
<?php
function flipAndGroup($input) {
$outArr = array();
array_walk($input, function($value, $key) use (&$outArr) {
if(!isset(
$outArr[$value]) || !is_array($outArr[$value])) {
$outArr[$value] = [];
}
$outArr[$value][] = $key;
});
return
$outArr;
}
?>

Example:
<?php
$users_countries
= array(
'username1' => 'US',
'user2' => 'US',
'newuser' => 'GB'
);
print_r(flipAndGroup($users_countries));
?>

Returns:
Array
(
[US] => Array
(
[0] => username1
[1] => user2
)

[GB] => Array
(
[0] => newuser
)
)

<< Back to user notes page

To Top