PHP associative array push
There is a function in PHP array_push(array $array, mixed $item). The use of this function is, if we want to add an item in an existing array. So lets say I have an array
$myarray = array('foo', 'bar');
Now if I will do something like this
array_push($myarray, 'hello');
My new array will be
Array(
[0] => foo
[1] => bar
[2] => hello
)
But if I say my previous array was
$myarray = array('f' => 'foo', 'b' => 'bar');
and now if I’ll use array_push($myarray, 'hello');
my array will be like
Array (
[f] => foo
[b] => bar
[0] => hello
)
That’s fine, but what If I want to push some items with keys. Like in the above example if I want to make my array like
Array (
[f] => foo
[b] => bar
[h] => hello
)
Well, don’t worry for this you can use this function
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
and to use this
$myarray = array_push_assoc($myarray, 'h', 'hello');
Cheers
function array_push_assoc(&$array, $key, $value){
$array[$key] = $value;
return $array;
}
Thanx!
Thanks — there is a big problem with your code, though, which kanel (the first commenter) pointed out. You should pass $array by reference to your function, or else you just end up with an empty array.
Otherwise, works great and is much more compact than other solutions I’ve seen out there.
Thank you SOO MUCH FOR THIS!! I REALLY APPRECIATE IT!! LOOKING FOR THIS ALL NIGHT!
function array_push_multi_assoc($array, $key, $key2, $value){
$array[$key][$key2] = $value;
return $array;
}
This also works for mutli-dem arrays too!
It’s just what I was looking for!
Thanks a lot!
thanks,…
Thank you. I searched all over the place but could not find the solution. Thanks
y so long code.. just use
$myarray["name"] = “myname”
a new array key ‘name’ would be created with value ‘myname’
Thanks it’s very useful for me.
Thank you!