Replace element in an associtive array
Posted: Wed Nov 01, 2006 10:58 am
I have an array ($a) that looks like thisand I want to replace 'bar' with this array ($new):producing this:As you can see need to preserve the order.
Either of these can do the replacement:But require me to specify an integer array position. As I don't know the position of the element I want to replace, this is a problem. Short of foreaching through the array incrementing a counter, getting such an integer (the internal array position of a associative key) seems impossible.
Help!
Code: Select all
Array
(
[foo] => 4
[bar] => 6
[zim] => 7
)Code: Select all
Array
(
[gir] => 5
[gaz] => 9
)Code: Select all
Array
(
[foo] => 4
[gir] => 5
[gaz] => 9
[zim] => 7
)Either of these can do the replacement:
Code: Select all
$b = array_merge(array_slice($a, 0, 1), $new, array_slice($a, 2));
// or
$b = array_splice($a, 1, 1, $new);Help!