tags:

views:

233

answers:

3

Say I have an associative array:

"color" => "red"
"taste" => "sweet"
"season" => "summer"

and I want to introduce a new element into it:

"texture" => "bumpy"

behind the 2nd item but preserving all the array keys:

"color" => "red"
"taste" => "sweet"
"texture" => "bumpy" 
"season" => "summer"

is there a function to do that? Array_splice() won't cut it, it can work with numeric keys only.

+1  A: 

I'm not sure if there is a function for that, but you can iterate through your array, store the index and use array_push.

Ben Fransen
+2  A: 

Well, you can rebuild the array from scratch. But the easiest way to go through an associative array in a particular order is to keep a separate ordering array. Like so:

$order=array('color','taste','texture','season');
foreach($order as $key) {
  echo $unordered[$key];
}
dnagirl
+4  A: 

I think you need to do that manually:

# Insert at offset 2
$offset = 2;
$newArray = array_slice($oldArray, 0, $offset, true) +
            array('texture' => 'bumpy') +
            array_slice($oldArray, $offset, NULL, true);
soulmerge
I ended up doing it this way. Thanks.
Pekka