OneBite.Dev - Coding blog in a bite size

Add New Item In Array In PHP

Code snippet for how to Add New Item In Array In PHP with sample and detail explanation

In PHP, arrays play a crucial role in storing multiple values in a single variable. This article provides a simple way of adding new elements or items to an array in PHP, a fundamental concept for any PHP developer.

Code snippet for Addition of New Items in Array

<?php
   // Define an array
   $color = array('Red', 'Green', 'Blue');

  // Add new item at the end of the array
  array_push($color, 'Yellow');

  print_r($color);

?>

In the example above, ‘Yellow’ is the new item added to the ‘color’ array.

Code Explanation for Addition of New Items in Array

In the above code snippet, $color is an array that contains three elements: ‘Red’, ‘Green’, and ‘Blue’.

To add a new item to the array in PHP, you can use the array_push() function. This function takes an array as its first parameter, followed by any number of elements you want to add.

Hence, array_push($color, 'Yellow'); adds the string ‘Yellow’ to the existing $color array.

Finally, the print_r function is used to print the contents of the color array in human-readable format.

When we print the $color array after pushing a new item to it, it will give us an array of four elements, i.e., ‘Red’, ‘Green’, ‘Blue’, and ‘Yellow’.

So, to summarize, the array_push() function in PHP is an easy and efficient way to add new elements or items on an existing array.

php