note 97900 deleted from function.array-flip by danbrown
| From: | danbrown@php.net | Date: | Fri, 14 May 2010 15:02:46 +0000 |
| Subject: | note 97900 deleted from function.array-flip by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-169243@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
Further to:
benles -> crescentfreshpot -> mikeb
To flip an array without losing duplicate values and get a consistent data structure, with or with
out duplicates.
<?php
function array_invert($arr)
{
$flipped = array();
foreach( $arr as $key => $val ) {
$flipped[$val][] = $key;
}
return $flipped;
}
$a = array(
'orange' => 'fruit',
'milk' => 'dairy',
'apple' => 'fruit',
'banana' => 'fruit'
);
print_r(array_invert($a));
/*
Array
(
[fruit] => Array
(
[0] => orange
[1] => apple
[2] => banana
)
[dairy] => Array
(
[0] => milk
)
)
*/
?>