PHP

Add To An Array Using PHP Examples

No programmer or developer can deny the importance and usefulness of arrays, regardless of the programming language used. A very basic, yet important concept is to add element to array using PHP. So do you know how to add an item to an empty array or simply add to an array with pre-existing elements? If not, then this article is for you. In this example, I am going to show how to use PHP to add to an array.

How to use PHP to Add An Element to An Array

Let’s look at how to add item to array by means of an example. For this, we will start by creating an empty array. And then we will see step-by-step, how to add individual items to the array. Once we are done adding elements to array using PHP, we will output the resultant array just to make sure that we did everything right. So here it goes:

<?php 
//Declare an empty array
$my_fruits_array = array();

//Add an item to the array
$my_fruits_array[] = 'apple';

//Add second item to the array
$my_fruits_array[] = 'mango';

//Add third item to the array
$my_fruits_array[] = 'grapes';

//Print the contents of the array. Use the <pre> tags to output the array in readable format.
echo '<pre>';
print_r($my_fruits_array);
echo '</pre>';
?>

As you can see from the above code, we are adding items to the array, one-by-one & at the end, we are showing echoing the output after adding a value to an array.

Your Turn!

Do you know of any other ways to PHP to add an element to an array? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*