How to add element to php array

Webee Cafe
How to add element to php array

Adding an element to PHP array and removing an element from php array is very simple. PHP has in-built function to perform this. A function array_push() is used to add an element to PHP array

Creating an array:

$custom_array = ['a','b','c'];

or

$custom_array = array('a','b','c');


Add an element to an array:

In php array_push function used to add an element to array. Syntax of array_push is

array_push(array, var);

If you want to add 'd' to $custom_array

$element='d';

array_push($custom_array , $element);

Result is:

Array ( [0] => a [1] => b [2] => c [3] => d )


Remove an element from array:

If you want to remove 'b' from $custom_array use unset function:

unset($custom_array [1]);

Result is 

Array ( [0] => a [2] => c )




Leave a reply