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
Posted in PHP

18 thoughts on “PHP associative array push

  1. 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.

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

    This also works for mutli-dem arrays too!

  3. Pingback: Rewriting URLs in WordPress: Tips and Plugins | Best Web Consulting company in Nashik, India with Creative and Professional Website Design, Content Management Systems, Wordpress Experts, Ecommerce SEO, and more..

  4. Pingback: Rewriting URLs in WordPress: Tips and Plugins

  5. Pingback: Rewriting URLs in WordPress: Tips and Plugins | Philterest

  6. Pingback: Rewriting URLs in WordPress: Tips and Plugins | Android News

  7. Pingback: Rutweb Technology : Rewriting URLs in WordPress: Tips and Plugins

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 )

Google+ photo

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

Connecting to %s