PHP Add to Array: Methods, Keys, and Performance
Use empty square brackets ($array[] = $value) to append one element to an indexed array in PHP. For an associative array, assign the value to a key with $array[$key] = $value. You can append several values without a loop using array_push($array, ...$values), or put them at the beginning with array_unshift($array, ...$values). To combine arrays, use the spread operator ([...$array, ...$newItems]) in modern PHP or call array_merge($array, $newItems).
PHP arrays preserve insertion order, but these operations handle keys differently. Some change the original array; others create a new one. Those differences matter when you need to keep integer keys or add many elements in a loop.
Appending Elements with Square Brackets
For a single element, empty square brackets are the simplest and fastest way to append:
$logs = ["boot", "init"];
$logs[] = "ready";
// Result: ["boot", "init", "ready"]
If $logs is empty when you run this code, PHP creates the array and assigns "ready" to index 0. If $logs already contains integer keys, PHP finds the highest integer key currently in the array and assigns the new element to that index plus one.
$items = [10 => "first", 20 => "second"];
$items[] = "third";
// $items[21] contains "third"
The PHP array types documentation explains how PHP chooses the next index. Unsetting the element with the highest key does not lower the internal counter. The next append still uses the integer after the highest key that has existed in that array instance:
$queue = [0 => "alpha", 1 => "beta"];
unset($queue[1]);
$queue[] = "gamma";
// $queue[2] contains "gamma", not $queue[1]
For a single value, square brackets also avoid a function call. This is the form the PHP manual recommends over array_push() for one element.
Appending Multiple Elements with array_push()
Pass multiple values to array_push() to append them in one expression:
$fruits = ["apple"];
$count = array_push($fruits, "banana", "cherry", "date");
// $fruits now holds ["apple", "banana", "cherry", "date"]
// $count is 4
As the PHP array_push manual explains, the first argument is the target array, passed by reference. The return value is the new element count.
You can also use argument unpacking with array_push() to append one list onto another in place:
$queue = ["job_1", "job_2"];
$batch = ["job_3", "job_4", "job_5"];
array_push($queue, ...$batch);
This changes $queue in place. Array unpacking expressions are also common in modern codebases, where developers often prefer their readability.
Prepending Elements to the Front of an Array
Use array_unshift() to put elements at the beginning of an array:
$steps = ["compile", "package"];
$newLength = array_unshift($steps, "lint", "analyze");
// $steps is now ["lint", "analyze", "compile", "package"]
// $newLength is 4
Key Reindexing in Prepending
Check your keys before using array_unshift(). It renumbers every numerical key, starting from zero and counting upwards. Literal string keys stay as they are:
$records = [
"user_1" => ["name" => "Alice"],
42 => ["name" => "Bob"],
"role" => "admin",
];
array_unshift($records, ["name" => "System"]);
// Numerical key 42 becomes 1.
// The new item gets key 0.
// String keys "user_1" and "role" remain unchanged.
If those integer keys are IDs your application needs, prepending this way will replace them with zero-based sequence numbers.

The Quadratic Performance Trap of array_unshift()
Appending an element with $array[] = $value has amortized O(1) cost. An occasional resize can cost more.
Each call to array_unshift() does work proportional to the existing array size, including renumbering numeric keys. In a loop, each prepend has a larger array to process. Building a list this way can take quadratic time overall.
// Inefficient pattern: O(N^2) execution time
$results = [];
foreach ($incomingFeed as $item) {
array_unshift($results, $item);
}
To build a reversed collection or prepend a series of items, use $results[] = $item inside the loop. Call array_reverse() once after the loop finishes. Appending and then reversing takes linear O(N) time.
Worked Example: Refactoring Prepending Loops
Here is a common scenario where log entries or transactional events need to be displayed in reverse chronological order.
Before: Inefficient array_unshift Inside a Collection Loop
function collectRecentEvents(iterable $eventStream): array
{
$events = [];
foreach ($eventStream as $event) {
if ($event->isValid()) {
array_unshift($events, $event->payload());
}
}
return $events;
}
In this implementation, every new valid event requires work across previously collected events. The cost grows as the list grows.
After: Fast Bracket Append with a Single Reverse
function collectRecentEvents(iterable $eventStream): array
{
$events = [];
foreach ($eventStream as $event) {
if ($event->isValid()) {
$events[] = $event->payload();
}
}
return array_reverse($events);
}
The revised code collects elements with $events[] = $event->payload(), then reverses the array once at the end. That avoids repeated prepends while keeping the same output order and validation check.
Adding Elements to Associative Arrays
An associative array stores values under string keys or custom integer keys. Put the key inside square brackets to add an entry or update its value:
$user = [
"id" => 101,
"name" => "Rodney",
];
// Add a new key
$user["email"] = "rodney@example.com";
// Update an existing key
$user["name"] = "Rodney Renner";
If the key does not exist, PHP adds the entry to the array. If the key already exists, PHP overwrites the existing value.
Insertion Order and Hash Table Behavior
In PHP, arrays preserve insertion order regardless of the keys used. Assigning a new key adds that entry at the end of the iteration order.
$config = [];
$config["timeout"] = 30;
$config["retries"] = 3;
$config["debug"] = false;
// Iterating $config yields "timeout", then "retries", then "debug"
Reassigning an existing key changes its value but keeps its position in the iteration order. Ryan Parman's 2011 article on better object-oriented arrays looks at how developers structured complex arrays before typed objects became common.
Key Type Juggling and Coercion Pitfalls
PHP automatically converts certain key types when writing to arrays:
- String values containing valid decimal integers are cast to integer keys. For example,
$array["42"] = "val"writes to$array[42]. - Floats are cast to integers by truncating the fractional component. For example,
$array[8.95] = "val"writes to$array[8]. - Booleans are cast to integers. A key of
truebecomes1, andfalsebecomes0. nullis cast to an empty string"".
$lookup = [];
$lookup["10"] = "integer-coerced";
$lookup[10] = "overwritten";
// $lookup contains only one element: [10 => "overwritten"]
These conversions can cause bugs with identifiers you think of as strings, including numeric user IDs, postal codes, and product SKUs. The postal code "01234" stays a string because of its leading zero. PHP converts "12345" to an integer.
A static analysis tool such as PHPStan can check array shapes and help catch unintended key types.
Inserting Elements at an Arbitrary Position
Use array_splice() to insert an element into the middle of an indexed array while keeping the existing values:
$pipeline = ["parse", "validate", "deploy"];
// Insert "lint" at offset 1 without deleting elements
array_splice($pipeline, 1, 0, ["lint"]);
// $pipeline is now ["parse", "lint", "validate", "deploy"]
The parameters to array_splice() are:
- The target array passed by reference.
- The starting integer offset.
- The length of the segment to remove, which must be
0when inserting without removal. - The replacement value or array of values to insert.
array_splice() renumbers numerical keys so they remain contiguous. It also shifts every element after the insertion point in memory, giving a splice an O(N) cost. Repeated insertions into the middle of a large array can be expensive.
Merging and Combining Arrays
Data processing pipelines and configuration loaders often need to combine arrays. The three main options in PHP are array_merge(), the union operator (+), and the spread operator (...). Choose based on what should happen to the keys.

Combining Arrays with array_merge()
The array_merge() function joins one or more arrays sequentially:
$baseConfig = ["host" => "localhost", "port" => 3306];
$overrides = ["port" => 3307, "database" => "production"];
$finalConfig = array_merge($baseConfig, $overrides);
// Result: ["host" => "localhost", "port" => 3307, "database" => "production"]
The PHP array_merge manual gives two rules for keys:
- String keys: If two arrays share a string key, the value from the later array overwrites the value from the earlier array.
- Integer keys: All integer keys are renumbered starting from zero, regardless of whether they overlap.
$listA = [10 => "ten", 20 => "twenty"];
$listB = [30 => "thirty"];
$combined = array_merge($listA, $listB);
// Result: [0 => "ten", 1 => "twenty", 2 => "thirty"]
Use a different method if you need to keep the original integer keys.
The Array Union Operator (+)
The union operator (+) combines arrays while preserving keys from both sides:
$defaults = [0 => "none", 1 => "read", 2 => "write"];
$custom = [2 => "admin", 3 => "superadmin"];
$union = $custom + $defaults;
// Result: [2 => "admin", 3 => "superadmin", 0 => "none", 1 => "read"]
The union operator takes keys from the left-hand array first. If a key already exists on the left, the corresponding element from the right-hand array is ignored. Unlike array_merge(), the union operator does not renumber integer keys and does not overwrite existing string keys.
The Modern Spread Operator (...$array)
PHP 7.4 introduced array unpacking with the spread operator (...). The PHP Spread Operator for Array RFC documents the syntax. You can write an array expression with another array unpacked inside it:
$coreModules = ["auth", "router"];
$fullModules = ["bootstrap", ...$coreModules, "cache"];
// Result: ["bootstrap", "auth", "router", "cache"]
Array unpacking initially supported only numerical keys. PHP 8.1 added support for string keys through the PHP Array Unpacking with String Keys RFC. In PHP 8.1 and later, a string key in an unpacked array overwrites an earlier entry with the same key, just as it does with array_merge():
$defaultHeaders = ["Accept" => "application/json", "X-App" => "v1"];
$customHeaders = ["X-App" => "v2", "Authorization" => "Bearer token"];
$requestHeaders = [...$defaultHeaders, ...$customHeaders];
// Result: ["Accept" => "application/json", "X-App" => "v2", "Authorization" => "Bearer token"]
Spread syntax also lets you place individual elements before, between, or after unpacked arrays in a single expression. Both spread syntax and array_merge() create a new array; benchmark your own workload before choosing between them for speed.
$tags = ["php", "web"];
$allTags = ["programming", ...$tags, "backend"];
Performance and Memory Allocation in the Zend Engine
With array_merge() or spread syntax, each operation allocates a new result array. Merging on every pass through a loop can mean repeatedly copying a collection as it grows.
// Appending in a loop
$items = [];
for ($i = 0; $i < 100_000; $i++) {
$items[] = $i;
}
The Zend Engine maintains an internal element counter on every array. As explained in our guide on PHP array length, calling count() reads this stored counter in constant time rather than counting elements on demand.
If an application handles many requests, profile its array operations and memory allocations when investigating a bottleneck. Our guide to PHP profiling covers tools and techniques for checking whether repeated copies or reallocations account for excessive memory use in production requests.
Step-by-Step Decision Guide: Choosing the Right Approach
The choice depends on where the values belong and which keys you need to keep:
- Appending a single value to an indexed array: Use empty square brackets
$array[] = $value. This avoids function-call overhead. - Appending multiple values in one statement: Use
array_push($array, ...$values)or array unpacking[...$array, ...$newValues]. - Prepending values to the beginning: Use
array_unshift($array, ...$values)for one-off operations. If prepending repeatedly inside a loop, append with$array[] = $valueinstead and callarray_reverse()once after the loop finishes. - Setting a specific key or updating an associative array: Use explicit assignment
$array[$key] = $value. - Merging arrays while overwriting duplicate string keys and renumbering numeric keys: Use spread syntax
[...$first, ...$second]in PHP 8.1+ orarray_merge($first, $second). - Merging arrays while strictly preserving integer keys: Use the array union operator
$first + $second, placing the array with higher priority on the left side. - Inserting values into the middle of an array: Use
array_splice($array, $offset, 0, $elements).
Common Mistakes to Avoid
These four mistakes come up when array operations meet loops, database keys, or variables of the wrong type.
1. Calling array_push() for Single Values in Tight Loops
Writing array_push($list, $item) inside a loop adds unnecessary function-call overhead. Use $list[] = $item for single-element appends.
2. Expecting array_merge() to Preserve Integer Keys
An array may use database primary keys or status codes as its keys. Calling array_merge() on those sets renumbers every integer key from zero, losing the association between each ID and its value. Use the union operator (+) or loop over the entries manually when those keys must survive.

3. Relying on Deprecated Autovivification from Boolean False
Prior to PHP 8.1, assigning an element to a variable containing boolean false automatically turned that variable into an array:
$data = false;
$data[] = "new_value"; // Conversion from false is deprecated in PHP 8.1+
PHP 8.1 deprecated automatic conversion of false to an array, as noted in the PHP migration guide. Appending to an undefined variable or a variable holding null continues to create an array without triggering that deprecation. Still, initializing $data = []; explicitly is good practice because it keeps variable types predictable and makes your intent clear.
4. Passing Non-Array Variables to array_push() or array_unshift()
In PHP 7, passing null or a non-array variable to array_push() produced a warning and returned null. In PHP 8.0 and later, passing an invalid type throws a fatal TypeError:
$items = null;
array_push($items, "value"); // Throws TypeError: array_push(): Argument #1 ($array) must be of type array
Initialize the target variable as an array before calling functions that modify it.
Frequently Asked Questions
How do I add multiple items to an array in PHP without a loop?
Use array_push($array, $item1, $item2, $item3) to append several elements in place. To create a new combined array in PHP 7.4 and later, use the spread operator: $combined = [...$array, $item1, $item2, $item3].
Does array_push work with associative key-value pairs?
No. array_push() only appends values and assigns numerical keys sequentially. To add key-value pairs to an associative array, assign each key directly using $array[$key] = $value, use the union operator $array + [$key => $value], or unpack associative arrays with [...$array, $key => $value] in PHP 8.1+.
How do I prepend an item without reindexing numerical keys?
Because array_unshift() always reindexes numerical keys to start from zero, use the array union operator instead. Place the new item in an array with its intended key on the left side of the union:
$original = [10 => "ten", 20 => "twenty"];
$prepended = [5 => "five"] + $original;
// $prepended preserves keys 5, 10, and 20
What is the performance difference between array_merge() and spread syntax?
It depends on the inputs and PHP version. Both [...$a, ...$b] and array_merge($a, $b) create a new array, and neither is always faster. Choose the key behavior and syntax that suit the code, then profile if the operation is a bottleneck. Spread syntax can also unpack an iterable such as a generator; array_merge() requires arrays.
How do I add elements to an array without mutating the original variable?
Empty brackets ($array[] = $val) and array_push() both change the target array. For an immutable programming pattern, where data stays unchanged in place, use array unpacking to return a new array:
$original = ["alpha", "beta"];
$updated = [...$original, "gamma"];
// $original remains ["alpha", "beta"]
// $updated contains ["alpha", "beta", "gamma"]