Current Location: Home> Latest Articles> Comprehensive Guide to Adding Elements to PHP Arrays

Comprehensive Guide to Adding Elements to PHP Arrays

M66 2025-11-06

How to Add Elements to Arrays in PHP

In PHP programming, adding elements to an array is a common task. The two main methods are using bracket syntax and the array_push() function.

Adding Array Elements Using Bracket Syntax

$array = [];
$array[] = 'Value1';
$array[] = 'Value2';

After executing the code above, an array with two elements will be created: ['Value1', 'Value2'].

Adding Array Elements Using the array_push() Function

$array = [];
array_push($array, 'Value1');
array_push($array, 'Value2');

This method also creates an array with two elements: ['Value1', 'Value2'].

Notes

  • For arrays with numeric keys, using bracket syntax will automatically add new elements to the end of the array.
  • For arrays with non-numeric keys, using bracket syntax will overwrite existing elements with the same key.
  • The array_push() function always adds new elements to the end of the array.

These are the common methods for adding elements to arrays in PHP. Mastering these two techniques allows more flexible array manipulation.