php

Add item to array PHP

Adding items to an array in PHP is a relatively simple task that can be accomplished in a number of different ways. The most common way to add an item to an array is by using the array_push() function, which adds an item to the end of an array. Other ways to add items to an array include using the array_unshift() function, which adds an item to the beginning of an array.

<?php
    // create an array
    $my_array = ["apple", "banana"];

    // add new item "orange" to array
    array_push($my_array, "orange");

    print_r($my_array);
?>

Output

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

PHP inbuilt function array_push() can be used to add items to an array. It takes a minimum of two required parameters as $array_name which is the name of the array in which the item is to be added and $item which is to be added to the array.

Add multiple items to array using array_push() function

You can pass more than one item to array_push to be added to the array like below

<?php
  $subjects = ["Math", "Physics"];
  
  array_push($subjects, "English", "Chemistry");
  
  print_r($subjects);
?>

Output

Array
(
    [0] => Math
    [1] => Physics
    [2] => English
    [3] => Chemistry
)

Add an item at the beginning of array using array_unshift() function

If you need to add an item to the beginning of an array in PHP, you can do so using the array_unshift() function. This function takes an array and adds the new item to the beginning of the array. The new item will be the first item in the array.

<?php
  $subjects = ["Math", "Physics"];
  
  array_unshift($subjects, "English");
  
  print_r($subjects);
?>

Output

Array
(
    [0] => English
    [1] => Math
    [2] => Physics
)

Add multiple elements at the beginning of an array

<?php
  $subjects = ["Math", "Physics"];
  
  array_unshift($subjects, "English", "Chemistry");
  
  print_r($subjects);
?>

Output

Array
(
    [0] => English
    [1] => Chemistry
    [2] => Math
    [3] => Physics
)
Was this helpful?