Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an associative array from another array's values only - PHP

I have a simple array where key is always followed by the value:

Array (
    [0] => x
    [1] => foo
    [2] => y
    [3] => bar
)

which I would like to convert to associative one:

Array (
    [x] => foo
    [y] => bar
)

What is the easiest and most elegant way to do this?

like image 220
errata Avatar asked Nov 01 '12 17:11

errata


1 Answers

To be memory efficient, and less calculations.

If the $input array has odd number of values, the last value will be NULL.

$result = array();

while (count($input)) {
    $result[array_shift($input)] = array_shift($input);
}
like image 135
Vicary Avatar answered Oct 24 '22 02:10

Vicary