How to Add Elements to Arrays in PHP

On this page we demonstrate and describe the various ways that you can add new elements to arrays in PHP. We cover square bracket syntax as well as the array_push and array_unshift functions. The array_splice function, which can also be used to add elements, is discussed elsewhere.

Square Bracket Syntax

When you want to add individual elements to the end of an array in PHP, square bracket syntax is the most efficient. You can include an index (integer or string) in the square brackets, or leave them empty, in which case PHP will use the next available integer. We demonstrate each of these options here:

$ar = array('Morie', 'Miki', 'Coco', 'Halo');
// integer index in square brackets
$ar[4] = 'Rudi';
// string index in square brackets
$ar['collie'] = 'Mollie';
// square brackets without index
$ar[] = 'Mittens';
print_r($ar);
/* print_r output (as seen in page source view):
Array
(
    [0] => Morie
    [1] => Miki
    [2] => Coco
    [3] => Halo
    [4] => Rudi
    [collie] => Mollie
    [5] => Mittens
) */

While you can use square brackets to add an element with a string index to an array, the functions below can only add numerically indexed elements.

array_push

You can use PHP's array_push function to add multiple elements to the end of an array. Pass the array as the first argument followed by any number of elements in the order in which you would like them to be added. The array_push function returns the number of elements in the modified array. We demonstrate by adding three new elements to the example array:

$ar = array('Morie', 'Miki', 'Coco', 'Halo');
// use array_push to add 3 elements to end of $ar
$num = array_push($ar, 'Rudi', 'Mittens', 'Pumkin');
// inspect return value of array_push
echo $num; // 7
print_r($ar);
/* Array
(
    [0] => Morie
    [1] => Miki
    [2] => Coco
    [3] => Halo
    [4] => Rudi
    [5] => Mittens
    [6] => Pumkin
) */

array_unshift

PHP's array_unshift function adds elements to the beginning of an array. As with array_push, pass the array first, followed by any number of elements you would like to add to the array. Arrays with numeric indexes have those indexes re-numbered starting from zero. We demonstrate adding two elements to the example array:

$ar = array('Morie', 'Miki', 'Coco', 'Halo');
// use array_unshift to add 2 elements to beginning of $ar
$num = array_unshift($ar, 'Lucky', 'Harlo');
// inspect return value of array_unshift
echo $num; // 6
print_r($ar);
/* Array
(
    [0] => Lucky
    [1] => Harlo
    [2] => Morie
    [3] => Miki
    [4] => Coco
    [5] => Halo
) */

array_splice

The array_splice function can be used to add elements anywhere in an array. Find out more.

Back to top