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