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

About these ads
    • kanel
    • July 27th, 2010

    function array_push_assoc(&$array, $key, $value){
    $array[$key] = $value;
    return $array;
    }

  1. Thanx! :)

    • Ryan
    • May 18th, 2011

    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.

    • Dan
    • June 12th, 2011

    Thank you SOO MUCH FOR THIS!! I REALLY APPRECIATE IT!! LOOKING FOR THIS ALL NIGHT!

    • Dan
    • June 14th, 2011

    function array_push_multi_assoc($array, $key, $key2, $value){
    $array[$key][$key2] = $value;
    return $array;
    }

    This also works for mutli-dem arrays too!

  2. It’s just what I was looking for!

    Thanks a lot!

    • agung susanto
    • March 10th, 2012

    thanks,…

    • Imran
    • March 28th, 2012

    Thank you. I searched all over the place but could not find the solution. Thanks

  3. y so long code.. just use
    $myarray["name"] = “myname”

    a new array key ‘name’ would be created with value ‘myname’

    • Juan Luis García
    • November 14th, 2012

    Thanks it’s very useful for me.

  4. Thank you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: