How to insert an element in php array?

Before few days, we have a requirement to insert an element in php array, after the initialization of it.

To fulfill our requirement, we have got two options.

First one is to use “$array[] = $var;” statement and second one is to use “array_push(array, value1[,value2…])”.

Where “array_push()” inserts one or more elements onto the end of array.

It has two arguments.

First one is an array in which we want to insert an element.

And the second one is the value, which needs to be inserted in an array.

So now here an example, which inserts an element in php array, using “$array[] = $var” and “array_push()”.

$test = array("First", "Second", "Third");
$test[] = "Fourth";
array_push($test, "Fifth");
print_r($test);

Hope this will help you.

Speak Your Mind

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

%d bloggers like this: