phparraysassociative-array

Convert every two values from a flat array into key-value pairs of a flat associative array


I have data in an index array where even index values are keys and odd are values, I am trying to make them key value in new array, see my code below.

Array
(
 [0] => firstName
 [1] => bob
 [2] => lastName
 [3] => alex
)

Code

$k = array();
$v = array();

foreach ($a as $key => $value) {
    if ($key % 2 == 0) {
        $k[] = $value;
    } else {
        $v[] = $value;
    }
}

Solution

  • Here's a solution using array_intersect_key to select the odd-numbered values and then the even-numbered values (using range to generate the list of key values), and then using array_combine to generate the output from those sets of values:

    $a = [ 'firstname' , 'bob' , 'lastname' , 'alex' ];
    
    $new = array_combine(
        array_intersect_key($a, array_flip(range(0, count($a) - 1, 2))),
        array_intersect_key($a, array_flip(range(1, count($a) - 1, 2)))
        );
    
    print_r($new);
    

    Output:

    Array (
      [firstname] => bob
      [lastname] => alex 
    )
    

    Demo on 3v4l.org