AppDividend
Latest Code Tutorials

PHP array_push() Function | PHP Add to Array Example

4

PHP array_push() is an inbuilt function that is used to add new elements to an array. The array_push() function is used to insert new items at the end of an array and get the updated number of array elements. An array stores multiple values in one single variable.

PHP add to array is an operation in which we append elements to the existing array. An array can contain many values under a single name, and you can access the values by referring to an index number.

In PHP, there are three types of array.

  1. Indexed arrays – Arrays with the numeric index.
  2. Associative arrays – Arrays with the named keys.
  3. Multidimensional arrays – Arrays that are containing one or more arrays.

Now, let’s see an example where we perform PHP add to array operations.

Understanding PHP array_push() Function

PHP array_push() function is used to insert new items at the end of an array and get the updated number of array elements. You may add as many values as you need.  Your inserted elements will always have numeric keys, even if the array itself has string keys. PHP array push() function has been introduced in PHP 4.

If we want to add more values to a PHP array, then we need to use the array_push() function, which inserts one or more elements to the end of an array.

The length of the array increases by the number of variables pushed. You can add one element or multiple elements at a time using array_push() function.

The array_push() treats an array as a stack and pushes the passed variables onto the end of an array. 

Syntax

The syntax for PHP Array Push is the following.

array_push(array,value1,value2...)

Parameters

An array parameter is required in which we will add the value.

The value1 parameter is also required, which is the value we will insert to the specified array.

The value2, value3, and so on are optional parameters. If we want to add the multiple values then and then we need to pass those parameters.

Return value

The array_push() function will return the length of new elements of an array.

Example

Let’s see an example.

Create one file called app.php and add the following code.

<?php

// app.php

$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];

$new = array_push($netflix, 'Shaft');

print_r($netflix);
echo $new."\n";

So, in the above code, we have defined one array called $netflix, which has four items.

Now, we have added the fifth item using array_push() function in PHP and then print the original array and the return value from the array_push function.

Now, we are running the file on the terminal. So go to the terminal and navigate up to the app.php file directory and type the following command to run the file.

php app.php

See the output.

PHP Array Push Example | Add Elements To An Array

That means, we have successfully added the Shaft show to the $neflix array.

Also, the array_push() function returns the length of the array. In our case, it is 5. Remember, the PHP Array index is starting from 0.

This operation is also called PHP add to the array.

Adding multiple values to PHP array

PHP array_push() function takes multiple elements and appends all the elements into the array. It will add in the order that they are added. It does not change its order.

<?php

// app.php

$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];

$new = array_push($netflix, 'Shaft', 'Mute', 'Clinical', 'Blue Jay', 'Candy Jar');

print_r($netflix);
echo $new."\n";

The output is the following.

Add Multiple Values To An Array in PHP

Adding values to the Associative Array

Let’s take a scenario where we are adding values to the Associative Array.

<?php

// app.php

$data = ['name' => 'Krunal', 'education' => 'BE'];
$new = array_push($data, 'Ankit', 'MCA');

print_r($data);
echo $new."\n";

See, the $data variable is Associative Array, and we have added two values to that array.

That means the first two items are associative, which have their key. But, from 3rd and 4th, they have indexes starting from 0. Let’s run the PHP file and see the output.

Add Values to the Associative Array in PHP

Adding array into an array in PHP

Okay, now let’s take a scenario, where we are adding a whole array inside an array and see the output.

<?php

// app.php

$dataA = ['name' => 'Krunal', 'education' => 'BE'];
$second = ['Facebook', 'Instagram'];
$newA = array_push($dataA, $second);

print_r($dataA);
echo $newA."\n";

The output is the following.

Add Array in the Array

See, it has added an array as a 3rd element, and it has its index, which is and 1.

So, right now, the dataA array is a multidimensional array.

Measuring PHP array length

In PHP, the total number of items in the array can be calculated by a couple of PHP functions count() and sizeof()whereas a sizeof() function is an alias of the master function count().

<?php

$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];

echo count($netflix);

See the following output.

➜  pro php app.php
4                                                                               
➜  pro

That means, we have four elements in the $netflix array. If we add more items inside the array, then the size of the array increasing and if we use array_pop() functionthen it will decrease the array length by one.

Pushing key and value in Associative Array

There is no array_push() equivalent for associative arrays because there is no way to determine the next key. We can use the array_push() method, but it will add the index starts from 0 and 1 and not the keys we desire. So if you want to push key and value, then you can do the following code.

<?php

$data = ['name' => 'Krunal', 'education' => 'BE']; 

$data['age'] = 26;
$data['business'] = 'IT';
print_r($data);

Output

Array
(
    [name] => Krunal
    [education] => BE
    [age] => 26
    [business] => IT
)

In the output, you can see that, and we can add multiple keys of your choice and not the ones that numeric keys php provides by default.

Pushing a value into the array automatically creates a numeric key for it. When inserting a key-value pair to the array, you already have the key, and you don’t need one to be created for you. That key is the numeric key, which starts from 0.

Adding element at the start of the Array

To add an element at the start of the array, you can use the PHP array_unshift() function. It appends the item at the beginning of the array at the index of 0.

<?php

$data = ['Python', 'Javascript', 'Golang'];
array_unshift($data, 'PHP');
print_r($data);

Output

Array
(
    [0] => PHP
    [1] => Python
    [2] => Javascript
    [3] => Golang
)

You can see that our new element “PHP” is added at the index position 0. 

The array_unshift() function adds new elements to the array. The new array values will be inserted at the beginning of the array. You can insert one value or as many as you like. Numeric keys will start at 0 and increase by 1 everytime new element is added. String keys will remain the same.

Finally, PHP array_push() function example is over.

Recommended Posts

PHP array_product()

PHP array_reverse()

PHP array_sum()

PHP array_walk()

PHP array_replace()

4 Comments
  1. goenergia says

    Thanks u help me.

  2. hk keluaran says

    Thank you for any other informative site. The place else may just I get that type of information written in such
    an ideal means? I’ve a undertaking that I am just now running on, and I’ve been on the glance out for such information.

  3. GARAMPOKER says

    If you are going for finest contents like I do,
    simply pay a visit this web site all the time since it provides quality contents,
    thanks

  4. Malcolm says

    Awesome! Its really amaziing paragraph, I have got much clesr idea
    about from this piece of writing.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.