note 54417 added to function.array-flip
| From: | crescentfreshpot at yahoo dot com | Date: | Sun, 03 Jul 2005 23:21:43 +0000 |
| Subject: | note 54417 added to function.array-flip | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-91380@lists.php.net to get a copy of this message | ||
Furthering benles note, if you don't want duplicate values to overwrite existing keys but need
non-duplicate values to be assigned like array_flip, use:
<?php
function array_invert($arr)
{
$flipped = array();
foreach(array_keys($arr) as $key) {
if(array_key_exists($arr[$key],$flipped)) {
$flipped[$arr[$key]] = array_merge((array)$flipped[$arr[$key]], (array)$key);
} else {
$flipped[$arr[$key]] = $key;
}
}
return $flipped;
}
$a = array(
'orange' => 'fruit',
'milk' => 'dairy',
'apple' => 'fruit',
'banana' => 'fruit'
);
print_r(array_invert($a));
/*
Output:
Array
(
[fruit] => Array
(
[0] => orange
[1] => apple
[2] => banana
)
[dairy] => milk
)
*/
?>
----
Manual Page -- http://www.php.net/manual/en/function.array-flip.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+54417
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54417&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54417&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54417&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54417&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54417&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54417&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+54417&report=yes
Search -- http://master.php.net/manage/user-notes.php