phparraysassociations

Create associative elements from every two elements of a flat indexed array


How can I convert this flat indexed array:

Array (
    [0] => fruit
    [1] => apple
    [2] => vegetable
    [3] => corn
    ... etc
)

into this associative array?

Array (
    [fruit] => apple
    [vegetable] => corn
    ... etc
)

Theoretically I'd need to set each even items as keys and every odd items as the values.


Solution

  • Loop through the array, incrementing the counter by 2, and then create the new array.

    $newArray = array();
    
    $len = count($oldArray);
    for($i = 0; $i < $len; $i+=2){
        $key = $oldArray[$i];
        $val = $i+1 < $len ? $oldArray[$i+1] : '';
    
        $newArray[$key] = $val;
    }