Create an associative array only from other array values ​​- PHP

I have a simple array that is always followed by a key:

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

which I would like to convert to associative:

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

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

+4
source share
6 answers

Memory efficiency and fewer calculations.

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

 $result = array(); while (count($input)) { $result[array_shift($input)] = array_shift($input); } 
+4
source

I do not know how effective this is, but:

 $newArray = array(); foreach(array_chunk($array, 2) as $keyVal){ list($key, $val) = $keyVal; $newArray[$key] = $val; } 

DEMO: http://codepad.org/VF8qHAhQ

+2
source
 $ar = Array("x","foo","y","bar"); $assoc = Array(); for($i=0;$i<count($ar);$i+=2){$assoc[$ar[$i]]=$ar[$i+1];} print_r($assoc); 

Output: array ([x] => foo [y] => bar)

+2
source

I'll start with a simple loop

 $arr = array( 'x', 'foo', 'y', 'bar' ); $result = array(); $end = count($arr); for ($i = 0; $i+1 < $end; $i+=2) { $result[$arr[$i]] = $arr[$i+1]; } var_dump($result); 

Output:

 array(2) { ["x"]=> string(3) "foo" ["y"]=> string(3) "bar" } 
+1
source

Assuming you want key / value pairs to be in each / other pattern, you can use:

 $data = array('x', 'foo', 'y', 'bar', 'z'); $new = array(); $end = count($data); for ($i = 0; $i < $end; $i += 2) { $new[$data[$i]] = (isset($data[$i + 1]) ? $data[$i + 1] : ''); } print_r($new); 

It gives:

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

This will jump to your data list and set the first value as the key and the next as the value. If there is no β€œnext” value (that is, the Finite element in the original array, which is not divisible by 2), it is empty.

A caveat to this approach is that if the same β€œkey” is examined more than once, it will be overwritten. This can be circumvented by adding if (isset($new[$data[$i]])) continue; as the first line in the loop.

+1
source

What about:

 $data = array('x','foo','y','bar'); $i = 0; $n = count($data) $newData = array(); while($i < $n) { $newData[$data[$i]] = $data[++$i]; } 
+1
source

Source: https://habr.com/ru/post/1443498/


All Articles