Add Array Items

Ma Mahalakshmi V Updated 14 Nov 2026
7 min read ·Lesson 83 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays 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 array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
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.