Add Array Items

La Lakshmi Priya Updated 19 Oct 2026
7 min read ·Lesson 127 of 143

PHP arrays grow dynamically — you never declare a size. New elements can be added at the end, at the beginning, at a specific position, or under a specific key. This lesson covers each technique, how PHP chooses keys for new elements, and how to add items safely.

WhereTechnique
At the end$array[] = $value; or array_push()
At the beginningarray_unshift()
At a specific positionarray_splice()
Under a specific key$array['key'] = $value;
As a new array (original unchanged)Spread [...$array, $value] or array_merge()

Adding to the End: $array[] = ...

Example

<?php
$cart = ['Gel Pen'];

$cart[] = 'Notebook';
$cart[] = 'Eraser';

print_r($cart);

Output

Array
(
    [0] => Gel Pen
    [1] => Notebook
    [2] => Eraser
)

Empty brackets mean "append with the next available integer key". This is the most common and fastest way to add a single element.

How the Next Key Is Chosen

PHP uses the largest integer key the array has ever had, plus one — even if that key has since been removed:

<?php
$numbers = [3 => 'three'];
$numbers[] = 'four';

$letters = ['a', 'b'];
unset($letters[1]);
$letters[] = 'c';

print_r($numbers);
print_r($letters);

Output

Array
(
    [3] => three
    [4] => four
)
Array
(
    [0] => a
    [2] => c
)
  • After key 3, the next key is 4.
  • After removing key 1, PHP does not reuse it; the next key is 2. Use array_values() if you need continuous indexes again.

Adding Several Items: array_push()

<?php
$cart = ['Gel Pen', 'Notebook'];

$newCount = array_push($cart, 'Eraser', 'Ruler');

echo "Items: $newCount\n";
echo implode(', ', $cart) . "\n";

Output

Items: 4
Gel Pen, Notebook, Eraser, Ruler
  • array_push() modifies the array in place (it takes it by reference) and returns the new number of elements.
  • It can add several values in one call.
  • For a single value, $cart[] = 'Eraser'; is preferred: it is shorter and avoids a function call.

Adding to the Beginning: array_unshift()

<?php
$queue = ['ORD-12', 'ORD-13'];

array_unshift($queue, 'ORD-URGENT');

print_r($queue);

Output

Array
(
    [0] => ORD-URGENT
    [1] => ORD-12
    [2] => ORD-13
)

array_unshift() inserts values at the start and re-numbers all integer keys. (String keys are kept.) Because every element moves, it is slower than appending for very large arrays — when you build a list in reverse order, it is usually better to append and call array_reverse() once at the end.


Adding at a Specific Position: array_splice()

<?php
$checkoutSteps = ['Cart', 'Address', 'Payment', 'Confirm'];

array_splice($checkoutSteps, 2, 0, ['Verify OTP']);

echo implode(' → ', $checkoutSteps) . "\n";

Output

Cart → Address → Verify OTP → Payment → Confirm

array_splice($array, $offset, $length, $replacement) with a length of 0 removes nothing and inserts the replacement at position $offset. The list is re-indexed automatically.


Adding Under a Specific Key

For associative arrays, assigning to a new key adds an element:

<?php
$user = ['name' => 'Asha', 'email' => 'asha@example.com'];

$user['phone'] = '+91 98765 43210';
$user['verified'] = true;

print_r($user);

Output

Array
(
    [name] => Asha
    [email] => asha@example.com
    [phone] => +91 98765 43210
    [verified] => 1
)

New keys are added at the end. If the key already exists, its value is replaced instead — the same syntax adds or updates. To add only when the key is missing, use ??=:

<?php
$settings = ['theme' => 'dark'];

$settings['theme'] ??= 'light';      // already set: unchanged
$settings['language'] ??= 'en';      // missing: added

print_r($settings);

Output

Array
(
    [theme] => dark
    [language] => en
)

Adding to Nested Arrays

<?php
$order = ['id' => 501, 'items' => [['name' => 'Gel Pen', 'qty' => 10]]];

$order['items'][] = ['name' => 'Notebook', 'qty' => 3];
$order['notes'][] = 'Gift wrap requested';   // 'notes' did not exist

echo count($order['items']) . " items\n";
print_r($order['notes']);

Output

2 items
Array
(
    [0] => Gift wrap requested
)

Appending to a nested key that does not exist ($order['notes'][]) creates that inner array automatically. This makes grouping data very concise (see the practical example below).


Creating a New Array Instead of Modifying

The spread operator and array_merge() build a new array, leaving the original unchanged:

<?php
$basics = ['Variables', 'Strings'];

$withArrays = [...$basics, 'Arrays'];
$withIntro = ['Introduction', ...$basics];
$combined = array_merge($basics, ['Loops', 'Functions']);

echo implode(', ', $withArrays) . "\n";
echo implode(', ', $withIntro) . "\n";
echo implode(', ', $combined) . "\n";
echo implode(', ', $basics) . "\n";

Output

Variables, Strings, Arrays
Introduction, Variables, Strings
Variables, Strings, Loops, Functions
Variables, Strings

This style is useful when the original must stay intact — for example, when building variations of a base configuration. See Array Spread Operator and Merge Arrays.


Adding Only Unique Values

Checking Before Adding

<?php
$tags = ['php', 'mysql'];

foreach (['laravel', 'php', 'api'] as $tag) {
    if (!in_array($tag, $tags, true)) {
        $tags[] = $tag;
    }
}

echo implode(', ', $tags) . "\n";

Output

php, mysql, laravel, api

Using Keys as a Set

in_array() searches the whole array each time, which becomes slow for large lists. Using the values as keys gives fast, automatic uniqueness:

<?php
$seen = [];

foreach (['php', 'mysql', 'php', 'api', 'mysql'] as $tag) {
    $seen[$tag] = true;
}

echo implode(', ', array_keys($seen)) . "\n";

Output

php, mysql, api

Assigning the same key twice simply overwrites it, so each tag appears once. Key lookups are fast regardless of array size.


What Can Be Appended To

<?php
$fresh = [];
$fresh[] = 'works';            // empty array: fine

$fromNull = null;
$fromNull[] = 'also works';    // null becomes an array

print_r($fresh);
print_r($fromNull);

Output

Array
(
    [0] => works
)
Array
(
    [0] => also works
)
  • Appending to null (or an undefined variable) creates a new array.
  • Appending to false also creates an array, but this has been deprecated since PHP 8.1 ("Automatic conversion of false to array is deprecated"). This often happens with functions that return false on failure.
  • Appending to a non-empty string, an integer, or an object is an error.

Initializing arrays explicitly with $list = []; avoids all of these cases.


Practical Example: Grouping Products by Category

<?php
$products = [
    ['name' => 'Desk Lamp', 'category' => 'Home'],
    ['name' => 'Notebook', 'category' => 'Stationery'],
    ['name' => 'Cushion', 'category' => 'Home'],
    ['name' => 'Gel Pen', 'category' => 'Stationery'],
    ['name' => 'Headphones', 'category' => 'Electronics'],
];

$byCategory = [];

foreach ($products as $product) {
    $byCategory[$product['category']][] = $product['name'];
}

ksort($byCategory);

foreach ($byCategory as $category => $names) {
    echo "$category (" . count($names) . "): " . implode(', ', $names) . "\n";
}

Output

Electronics (1): Headphones
Home (2): Desk Lamp, Cushion
Stationery (2): Notebook, Gel Pen

Step-by-Step Explanation

  1. $byCategory starts empty.
  2. $byCategory[$product['category']][] = $product['name']; does two things at once:
    • If the category key does not exist yet, PHP creates it with an empty array.
    • The product name is appended to that category's list.
  3. ksort() sorts the categories alphabetically by key.
  4. Products keep their original order within each category.

This one-line grouping pattern is used constantly — for example, to group orders by status, students by class, or log entries by date.


Common Mistakes

Assigning the Result of array_push()

$cart = array_push($cart, 'Pen');   // $cart becomes an integer!

Effect: array_push() returns the new count, so the array is replaced by a number.

Fix: Call it as a statement: array_push($cart, 'Pen');, or use $cart[] = 'Pen';.

Using + to Append to a List

Effect: [1, 2] + [3] gives [1, 2], because key 0 already exists.

Fix: Use [...$a, ...$b] or array_merge().

Expecting Removed Indexes to Be Reused

Effect: Gaps remain after unset(), even when new items are appended.

Fix: Re-index with array_values() when continuous indexes matter.

Appending to Unchecked Function Results

Effect: Deprecation notices (for false) or errors (for strings).

Fix: Initialize arrays explicitly and check function results.

Using array_unshift() in a Loop on Large Arrays

Effect: Every call re-indexes the entire array.

Fix: Append, then reverse once.


Best Practices

  • Use $array[] = $value; to append a single item.
  • Use array_push() only to append several items at once, and never assign its result to the array.
  • Use array_splice() to insert at a position and array_unshift() for the occasional prepend.
  • Use the $groups[$key][] = $value; pattern for grouping.
  • Use keys as a set for fast uniqueness checks.
  • Initialize arrays with [] before adding to them.

Official reference: https://www.php.net/manual/en/function.array-push.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning
Ask about this post
AI Ask about this post

Ask questions about Add Array Items and get answers drawn from it.

Signed-in readers only.