Adding element in an array in php

Last updated 2 years, 7 months ago | 401 views 75     5

Tags:- PHP

PHP | array_push() function

We can add elements to an array in an easy way. There is an inbuilt function array_push() in PHP which is used to add elements to the PHP array. With the help of the array_push() function, we can add one or more elements to an array. The function treats the array as a stack and pushes the passed element onto the end of an array. The length of the array increases by the number of elements pushed. The function always adds a numeric key to the pushed element.

Syntax

array_push($array, $val1, $val2, $val3....)

In the above syntax, $array is the array in which we want to add some element, and $val1, $val2, $val3... is a list of elements which we want to add to the array.

Let's see an example:

<?php
$arr=array("Dog","Cat");
array_push($arr,"Rat","Cow");
print_r($arr);
?>

The output of the above example is:

Array ( [0] => Dog [1] => Cat [2] => Rat [3] => Cow )

The above produce output with a numeric key. The key is in increasing order

Let's see an array with string keys:

<?php
$arr=array("a"=>"Dog","b"=>"Cat");
array_push($arr,"Rat","Cow");
print_r($arr);
?>

The output of the code above will be:

Array ( [a] => Dog [b] => Cat [0] => Rat[1] => Cow)

We can see that in the above output key value is a, b, 0 and 1. The inserted key value is numeric

The above array is an associative array where the key is self-defined, in this case, if we use the array_push() function to add an element in the array is not shot. so for an associative array, we have to use a different way to add elements to the array.

Here is the code for inserting an element in an associative array

<?php
$arr=array("a"=>"Dog","b"=>"Cat");
$arr['c'] = 'Rat';
$arr['d'] = 'Cow';
print_r($arr);
?>

The output of the code above will be:

Array ( [a] => Dog [b] => Cat [c] => Rat [d] => Cow )