Add Element Values to PHP Array: 5 Code Examples (2023)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Add Elements to Arrays Using PHP

There are several methods to add to an array in PHP. Using square brackets, array_push, and array_unshift function are the most common methods. The array_push & square brackets will add to the end of an array. You can add to associate arrays by setting a new key with values.

These methods differ in adding elements at different positions in an array. I have been used to array_push and use it most of the time to add multiple elements simultaneously.

By the end of this article, you’ll learn different ways of adding elements to an array.

Use Square Bracket Syntax to Add Values to PHP Arrays

The square bracket method is probably the most well-known method to add to an array in PHP. You can add individual elements by an integer, or a string index passed to the square brackets.

You can also empty the square brackets, and PHP will automatically add the elements to the next available index in the original array.

This method is preferable when adding a single element to the original array. It avoids the overhead of calling a function. However, for adding multiple values, this syntax could be daunting.

Square Bracket Method PHP Code Example

<?php
 
//Array with three elements.
$fruits = array('Apple','Orange','Mango');
 
//Square bracket syntax: Adding elements by an integer index.
$fruits[3] = "Watermelon";
 
//Square bracket syntax: Adding elements by a string index.
$fruits['Vegetable'] = 'Carrot';
 
//Square bracket syntax: No index
$fruits[] = 'Avocado';
 
//Output the array to console.
print_r($fruits);
 
/* Output
Array
(
    [0] => Apple
    [1] => Orange        
    [2] => Mango
    [3] => Watermelon    
    [Vegetable] => Carrot
    [4] => Avocado       
)
*/
?>

The code above covers all the possibilities to add to an array in PHP using this syntax. A remarkable feature is that PHP won’t throw an error even if you skip an index. The following code demonstrates this by skipping index 3.

<?php
//Array with three elements.
$fruits = array('Apple','Orange','Mango');
 
//Square bracket syntax: Adding elements by an integer index (Skipping index 3).
$fruits[4] = "Watermelon";
 
//Output the array to console.
print_r($fruits);
 
/* Output
Array
(
    [0] => Apple
    [1] => Orange
    [2] => Mango
    [4] => Watermelon
)
*/
?>

PHP is smart.

Next, we’ll use the array_push array function to add one or more elements to a PHP array.

Use array_push Array Function to Add Element to End of Array

PHP’s array_push function adds elements to the end of the array. The great thing about array_push is that you can add any number of elements to the end of an array. I prefer this function whenever I need to add multiple elements at one go. It’s pretty simple to use.

Array Append PHP Code Example

<?php
 
//Array with three elements.
$fruits = array('Apple','Orange','Mango');
 
//array_push: Adding three elements to the end of the $fruits array.
array_push($fruits,'Watermelon','Avocado','Strawberries');
 
 
//Output the array to console.
print_r($fruits);
 
/*
Array
(
    [0] => Apple       
    [1] => Orange      
    [2] => Mango       
    [3] => Watermelon  
    [4] => Avocado     
    [5] => Strawberries
)
*/
 
?>

We see how easily we add three items at once through the array_push array function. The only concern using array_push is that it adds by integer index only.

Next, we’ll see array_unshift.

It is the opposite of array_push because it will insert into the beginning of the array elements.

Option 3: Add to the beginning of an array with array_unshift

While array_push adds to the end of an array, PHP’s array_unshift adds elements to the start of an array. You can add any number of elements, and the array will reindex the elements every time. Let’s demonstrate this through code.

PHP Add Item to Array Using array_unshift Code Example

<?php
 
//Array with three elements.
$fruits = array('Apple','Orange','Mango');
 
//array_unshift: Adding three elements to the start of the $fruits array.
array_unshift($fruits,'Watermelon','Avocado','Strawberries');
 
 
//Output the array to console.
print_r($fruits);
 
/*Output
Array
(
    [0] => Watermelon  
    [1] => Avocado     
    [2] => Strawberries
    [3] => Apple       
    [4] => Orange      
    [5] => Mango       
)
*/
 
?>

See how neatly it adds the elements and reindexes the array. Next, we see array_splice which can add elements to an array at any specified index.

Option 4: Replace and add new items to the array with the array_splice

PHP’s array_splice is mainly used for removing and replacing elements in an array. It creates a new array based on the content of the old array.

However, there is a neat trick if you want to add to an array using this function. First, let’s understand the function and its arguments as specified in the official documentation.

array_splice(array,start,length,value)

Arguments

  • array –  Input array (Required)
  • start –  The offset value for specifying where the function should start replacing values.
  • length –  Specifies the number of elements to be replaced. 
  • value A replacement of the removed values from the array.

Passing zero to the length argument doesn’t remove elements from the array but adds at the specified start value. The array_splice function is robust because it can add elements at any position in an array, unlike array_push and array_unshift.

1. Adding at the middle of an array

The code here adds in the middle of an array at index 2. We specify an offset value of 2 and the function adds the elements at that position.

<?php
 
//Array with four elements.
$fruits = array('Apple','Orange','Mango','Watermelon');
 
//array_splice: Adding two elements to the $fruits array.
array_splice($fruits,2,0,['Avocado','Strawberries']);
 
 
//Output the array to console.
print_r($fruits);
 
/*Output
Array
(
    [0] => Apple       
    [1] => Orange      
    [2] => Avocado     
    [3] => Strawberries
    [4] => Mango       
    [5] => Watermelon  
)
*/
 
?>

Add element values to the start of an array

That’s how we can add to the start of an array using array_splice. A start value of zero sets the offset to the beginning of the array.

<?php
 
//Array with four elements.
$fruits = array('Apple','Orange','Mango','Watermelon');
 
//array_splice: Adding two elements to the $fruits array.
array_splice($fruits,0,0,['Avocado','Strawberries']);
 
 
//Output the array to console.
print_r($fruits);
 
/*Output
Array
(
    [0] => Avocado     
    [1] => Strawberries
    [2] => Apple       
    [3] => Orange      
    [4] => Mango       
    [5] => Watermelon  
)
*/
 
?>

Add array values to the end

Passing -1 to the start arguments sets the offset to the end of the array. However, the function adds elements all the way up from the second-last index position.

<?php
 
//Array with four elements.
$fruits = array('Apple','Orange','Mango','Watermelon');
 
//array_splice: Adding two elements to the $fruits array.
array_splice($fruits,-1,0,['Avocado','Strawberries']);
 
 
//Output the array to console.
print_r($fruits);
 
/*Output
Array
(
    [0] => Apple       
    [1] => Orange      
    [2] => Mango       
    [3] => Avocado     
    [4] => Strawberries
    [5] => Watermelon  
)
*/
 
?>

That’s all about the different methods to add to an array in PHP. We hope that you’ve enjoyed the article.

When to Use array_push vs Square Brackets to Append PHP Array

You will generally use the square brackets whenever needing to add single elements to arrays. It is more concise and has better performance (for larger arrays). On the other hand, array_push is the correct method when adding multiple values to an array.

  1. Readability: Both methods are easy to understand, but square brackets are more concise and often considered more readable for appending single elements.
  2. Performance: The square bracket method is generally faster than the array_push function, especially for large arrays, as the latter has the overhead of a function call. However, the performance difference is negligible for small arrays.
  3. Flexibility: array_push() You can add multiple elements simultaneously, while square brackets must be used multiple times to add more than one element. This can make array_push() more convenient when dealing with multiple values.

Best Practices:

  1. Use square brackets when adding a single element to an array, as it is more concise and performs better.
  2. If you need to add multiple elements, consider using array_push() for improved readability.
  3. Always consider the performance implications of each method when dealing with large arrays, as using the most efficient approach can improve the performance of your PHP application.

Want to explore further about PHP arrays?

We have many fun articles related to PHP arrays. You can explore these for learning more about arrays in PHP.

How to get the length of an array in PHP

How to print an array in PHP

Convert PHP array into a string with implode function

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.