note 126753 added to function.array-combine

From: Date: Sun, 09 Jan 2022 13:46:17 +0000
Subject: note 126753 added to function.array-combine
Groups: php.notes 
Request: Send a blank email to php-notes+get-217478@lists.php.net to get a copy of this message
Here a way to manage no uniqueness keys case. Values of duplicate keys are put in an array. <?php function array_combine_multi(array $keys, array $values) { if (count($keys) !== count($values)) { throw new Exception('Arrays count mismatch'); } $result = []; foreach ($values as $i => $value) { if (!isset($result[$keys[$i]])) { $result[$keys[$i]] = $value; } elseif (!is_array($result[$keys[$i]])) { $result[$keys[$i]] = [$result[$keys[$i]], $value]; } else { $result[$keys[$i]][] = $value; } } return $result; } $keys = ['key-1', 'key-2', 'key-3', 'key-2', 'key-2']; $values = ['value-1', 'value-2', 'value-3', 'value-4', 'value-5']; $result = array_combine_multi($keys, $values); print_r($result); /* Gives : Array ( [key-1] => value-1 [key-2] => Array ( [0] => value-2 [1] => value-4 [2] => value-5 ) [key-3] => value-3 ) */ ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.135 (proxied: 2a01:e0a:968:1840:a50e:f8e1:4366:9745) ---- Manual Page -- https://php.net/manual/en/function.array-combine.php Edit -- https://main.php.net/note/edit/126753 Del: integrated -- https://main.php.net/note/delete/126753/integrated Del: useless -- https://main.php.net/note/delete/126753/useless Del: bad code -- https://main.php.net/note/delete/126753/bad+code Del: spam -- https://main.php.net/note/delete/126753/spam Del: non-english -- https://main.php.net/note/delete/126753/non-english Del: in docs -- https://main.php.net/note/delete/126753/in+docs Del: other reasons-- https://main.php.net/note/delete/126753 Reject -- https://main.php.net/note/reject/126753 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#217478) next »