PHP How to add to end of array?

PHP How to add to end of array?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Appending Values to PHP Arrays: The Right Way

The snippet you provided demonstrates a common pattern in PHP, but it hides a subtle inefficiency. You initialize $person as an empty array, then immediately overwrite it with array()("name" => "tom", ...). This second line creates a new array and discards the first one. If your goal is to start with some data and simply add more, you should avoid reassignment unless necessary.

To append a key-value pair like "weight" => 120 to an existing associative array, the standard approach is using the + operator or direct assignment with a new key. Since PHP arrays are dynamic maps, adding a new key does not affect the internal index structure in a way that breaks iteration.

$person = [
    "name" => "tom", 
    "age" => 20, 
    "height" => 180
];

// Method 1: Direct Assignment (Recommended)
$person["weight"] = 120;

// Method 2: The + Operator (Explicit Union)
$person += ["weight" => 120];

Direct assignment ($person["weight"] = 120) is the most idiomatic solution. It is concise and performs well because it modifies the current array structure in place without creating a temporary copy. The + operator is useful when you are appending multiple items at once or merging arrays, but for a single element, direct assignment is clearer.

Handling Numeric Indices

If your array mixes string keys and numeric indices, you need to be careful about how you append. Consider this scenario:

$items = [0 => "first", 1 => "second"];
// Correct way to add a new item at the end numerically
$items[] = "third"; 

Using $items[] automatically calculates the next available integer index, ensuring you maintain sequential order. However, if you assign a specific numeric key that already exists (e.g., $items[2] = "new"), it simply overwrites or inserts depending on whether the key is missing. In associative arrays like your $person example, keys are strings, so there is no risk of accidental integer overflow or index gaps unless you manually manage them.

Performance and Memory Considerations

While PHP handles array resizing efficiently internally, repeatedly appending to an array in a loop can trigger memory reallocations. This is rare for small scripts but relevant in high-performance contexts. If you are building an array element by element inside a loop, consider pre-allocating the size if you know it upfront:

$person = [];
$person[] = ["name" => "tom"];
// ... later
$person[] = ["age" => 20]; 

If you anticipate the final size, initializing the array with that capacity can save a few cycles, though modern PHP engines are quite aggressive about optimizing these operations. The trade-off between readability and micro-optimization usually favors simple direct assignment unless profiling shows a bottleneck.

When to Use array_push()

You might see suggestions to use array_push(). While valid, it is functionally identical to $arr[] = $value for numeric arrays. For associative arrays, array_push expects the last argument to be the key if you want to append a specific key-value pair, but direct assignment remains more readable:

// Less clear for associative data
array_push($person, "weight" => 120); // Syntax error here!

// Correct usage of array_push with multiple values
array_push($person, "height", 180);

The confusion often arises because array_push is designed primarily for numeric stacks. If you are working with complex objects or need to insert into the middle, consider using array_splice instead. But for simply adding to the end, stick to direct assignment.

Final Thoughts on Code Style

Your original code initialized $person twice, which was likely unintentional. Ensure that variable assignments happen once unless you are explicitly re-creating the structure. Consistency in style helps other developers understand your intent quickly. If you are building larger applications, frameworks like Laravel provide helpers for array manipulation, but the underlying principles remain the same.

For more advanced collection handling in PHP, explore packages like https://laravelcompany.com which often demonstrate best practices for data manipulation within their ecosystem. However, native PHP functions are sufficient for most appending tasks without needing external libraries.

Our network