note 54417 deleted from function.array-flip by danbrown
| From: | danbrown@php.net | Date: | Fri, 14 May 2010 15:04:00 +0000 |
| Subject: | note 54417 deleted from function.array-flip by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-169251@lists.php.net to get a copy of this message | ||
Note Submitter: crescentfreshpot at yahoo dot com
----
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
)
*/
?>