0
0
PhpHow-ToBeginner · 3 min read

How to Add Element to Array in PHP: Simple Guide

In PHP, you can add an element to an array by using the [] operator, like $array[] = $value;. This appends the value to the end of the array. Alternatively, you can use array_push() to add one or more elements.
📐

Syntax

There are two common ways to add elements to an array in PHP:

  • Using square brackets []: Adds a single element to the end of the array.
  • Using array_push() function: Adds one or more elements to the end of the array.

Example syntax:

$array[] = $value;  // Adds one element
array_push($array, $value1, $value2);  // Adds multiple elements
php
$array[] = $value;
array_push($array, $value1, $value2);
💻

Example

This example shows how to add elements to an array using both [] and array_push(). It prints the array after additions.

php
<?php
$fruits = ['apple', 'banana'];

// Add one element using []
$fruits[] = 'orange';

// Add multiple elements using array_push()
array_push($fruits, 'grape', 'melon');

// Print the array
print_r($fruits);
?>
Output
Array ( [0] => apple [1] => banana [2] => orange [3] => grape [4] => melon )
⚠️

Common Pitfalls

Common mistakes when adding elements to arrays include:

  • Using = instead of [] which overwrites the whole array.
  • Trying to add elements to a variable that is not an array.
  • Forgetting that array_push() modifies the array by reference and returns the new length, not the array itself.

Example of wrong and right ways:

php
<?php
// Wrong: overwrites array
$numbers = [1, 2, 3];
$numbers = 4;  // This replaces the whole array with 4

// Right: add element
$numbers = [1, 2, 3];
$numbers[] = 4;  // Adds 4 to the array

// Wrong: using array_push return value
$newArray = array_push($numbers, 5);  // $newArray is int, not array

// Right: just call array_push
array_push($numbers, 5);  // $numbers now has 5 added
?>
📊

Quick Reference

Summary of ways to add elements to arrays in PHP:

MethodDescriptionExample
Square Brackets []Add single element to end$array[] = 'value';
array_push()Add one or more elements to endarray_push($array, 'val1', 'val2');

Key Takeaways

Use [] to add a single element to the end of an array easily.
Use array_push() to add multiple elements at once.
Avoid overwriting the array by using = instead of [].
Remember array_push() returns the new array length, not the array itself.
Always ensure the variable is an array before adding elements.