note 126524 added to function.array-flip

From: Date: Thu, 21 Oct 2021 13:05:04 +0000
Subject: note 126524 added to function.array-flip
Groups: php.notes 
Request: Send a blank email to php-notes+get-217096@lists.php.net to get a copy of this message
If you don't want to lose duplicates, and you're ok, with having the values in the flipped array in an array as well, you may use this: PHP 7.4 - ^8 <?php function array_flip_safe(array $array) : array { return array_reduce(array_keys($array), function ($carry, $key) use (&$array) { $carry[$array[$key]] ??= []; $carry[$array[$key]][] = $key; return $carry; }, []); } ?> PHP 7.0 - ^7.3 (Time to upgrade to PHP 8 ^^) <?php function array_flip_safe(array $array) : array { return array_reduce(array_keys($array), function ($carry, $key) use (&$array) { $carry[$array[$key]] = $carry[$array[$key]] ?? []; $carry[$array[$key]][] = $key; return $carry; }, []); } ?> PHP 5.4 - ^5.6 (Just don't) <?php function array_flip_safe(array $array) { return array_reduce(array_keys($array), function ($carry, $key) use (&$array) { if (!isset($carry[$array[$key]]) $carry[$array[$key]] = []; $carry[$array[$key]][] = $key; return $carry; }, []); } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.85.242 (proxied: 84.255.204.158) ---- Manual Page -- https://php.net/manual/en/function.array-flip.php Edit -- https://main.php.net/note/edit/126524 Del: integrated -- https://main.php.net/note/delete/126524/integrated Del: useless -- https://main.php.net/note/delete/126524/useless Del: bad code -- https://main.php.net/note/delete/126524/bad+code Del: spam -- https://main.php.net/note/delete/126524/spam Del: non-english -- https://main.php.net/note/delete/126524/non-english Del: in docs -- https://main.php.net/note/delete/126524/in+docs Del: other reasons-- https://main.php.net/note/delete/126524 Reject -- https://main.php.net/note/reject/126524 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#217096) next »