note 116714 added to function.array-combine

From: Date: Sun, 15 Feb 2015 10:59:01 +0000
Subject: note 116714 added to function.array-combine
Groups: php.notes 
Request: Send a blank email to php-notes+get-201734@lists.php.net to get a copy of this message
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 ) ) ---- Server IP: 72.52.91.14 Probable Submitter: 82.80.159.227 ---- Manual Page -- http://php.net/manual/en/function.array-combine.php Edit -- https://master.php.net/note/edit/116714 Del: integrated -- https://master.php.net/note/delete/116714/integrated Del: useless -- https://master.php.net/note/delete/116714/useless Del: bad code -- https://master.php.net/note/delete/116714/bad+code Del: spam -- https://master.php.net/note/delete/116714/spam Del: non-english -- https://master.php.net/note/delete/116714/non-english Del: in docs -- https://master.php.net/note/delete/116714/in+docs Del: other reasons-- https://master.php.net/note/delete/116714 Reject -- https://master.php.net/note/reject/116714 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#201734) next »