Created
July 6, 2017 09:17
-
-
Save qaharmdz/48b573967da8e5441765111401ef205b to your computer and use it in GitHub Desktop.
PHP array pair: odd as key, even as value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on https://www.sitepoint.com/community/t/reorganizing-an-array-odd-entries-as-key-even-entries-as-value/95548/2 | |
function array_pair($items) | |
{ | |
$results = array(); | |
foreach (array_chunk($items, 2) as $pair) { | |
list($key, $value) = $pair+[null,null]; // fix list() issue | |
$results[$key] = $value; | |
} | |
return $results; | |
} | |
$items = ['foo', 'bar', 'baz', 'cool', 'world']; | |
print_r($items); | |
array( | |
'foo' => 'bar', | |
'baz' => 'cool', | |
'world => null | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment