PHP create key => value pairs within a foreach

BobFlemming picture BobFlemming · May 10, 2011 · Viewed 120.5k times · Source

I want to create a key-value pairs in an array within a foreach. Here is what I have so far:

function createOfferUrlArray($Offer) {
    $offerArray = array();

    foreach ($Offer as $key => $value) { 
        $keyval = array($key => $value[4] );

        array_push($offerArray,$keyval);
    }

    return $offerArray;
}   

If I declare the array within the foreach, it will overwrites it on each iteration, but defining it outside the foreach doesn't work either and causes triplets:

array[0] => key => value
array[1] => key => value 

How do I make it so I only get key-value pairs like this?

key => value
key => value

Answer

Emil Vikström picture Emil Vikström · May 10, 2011

Something like this?

foreach ($Offer as $key => $value) { 
  $offerArray[$key] = $value[4];
}