Array Push Key And Value Php

3 min read

Adding a key and a value to a PHP array looks like a simple task until you try to do it with array_push() and discover that the function only accepts values, not keys. Even so, that single detail trips up thousands of developers every year, especially those coming from JavaScript, where obj[key] = value and arr. push(value) feel interchangeable. In PHP, arrays are a hybrid of lists and dictionaries, and the language gives you several distinct tools for inserting data — each with its own rules, side effects, and ideal use case. This guide walks through every reliable way to push a key and value into a PHP array, explains why array_push() behaves the way it does, and shows the pitfalls that silently corrupt data in production code.

Understanding How PHP Arrays Really Work

Before touching any function, you need a clear mental model. A PHP array is an ordered map: it associates keys with values, and every key is either an integer or a string. There is no separate "object" or "dictionary" type for keyed collections.

Not the most exciting part, but easily the most useful.

That means two arrays can look identical in code but behave differently:

$list = ['apple', 'banana', 'cherry'];      // keys: 0, 1, 2
$map  = ['fruit' => 'apple', 'veg' => 'carrot']; // keys: strings

PHP calls the first an indexed array and the second an associative array. Internally they are the same structure. The distinction matters because functions like array_push() are designed for the indexed case and quietly fall back to auto-incrementing integers when given an associative array.

What array_push() Actually Does

The signature is straightforward:

array_push(array &$array, mixed ...$values): int

It appends one or more values to the end of the array, assigns them the next available integer keys, and returns the new element count Easy to understand, harder to ignore..

$stack = ['a', 'b'];
$count = array_push($stack, 'c', 'd');

// $stack  = ['a', 'b', 'c', 'd']
// $count  = 4

Three things are worth noting:

  • The first argument is passed by reference, so it must be a real variable — you cannot pass a literal or a function result.
  • The function returns the new length, not the array itself, which is a common source of bugs when people write $new = array_push($arr, 'x');.
  • array_push() cannot assign string keys. There is no parameter for a key. Ever.

If you pass an associative array as a value, it becomes a nested array at a numeric index:

$user = ['name' => 'Ada'];
array_push($user, ['role' => 'admin']);

// ['name' => 'Ada', 0 => ['role' => 'admin']]

That is almost never what the developer intended. The role key is buried one level deep instead of sitting alongside name That's the part that actually makes a difference. Nothing fancy..

The Correct Way to Push a Key and Value

For associative inserts, the bracket syntax is the canonical solution:

$user = [];
$user['name'] = 'Ada';
$user['role'] = 'admin';
$user['active'] = true;

This is fast, readable, and works for both new keys and existing ones. If the key already exists, the value is overwritten — no warning, no error. That behavior is intentional and is the reason bracket assignment is the default choice for building arrays incrementally inside loops.

$totals = [];
foreach ($orders as $order) {
    $totals[$order['customer']] = ($totals[$order['customer']] ?? 0) + $order['amount'];
}

The ?? null-coalescing operator keeps the accumulation safe on the first iteration.

Five Alternatives Worth Knowing

1. The Union Operator +=

$defaults = ['theme' => 'light', 'lang' => 'en'];
$config   = ['theme' => 'dark'];

$merged = $config + $defaults;
// ['theme' => 'dark', 'lang' => 'en']

The union operator adds keys that do not already exist and never overwrites. In real terms, this makes it perfect for merging defaults into user-supplied configuration. The order matters: keys on the left win.

2. array_merge()

$merged = array_merge($config, $defaults);
// ['theme' => 'light', 'lang' => 'en']

Here the opposite happens — later arrays overwrite earlier ones for string keys. Numeric keys are renumbered sequentially, which is a frequent surprise when merging lists Easy to understand, harder to ignore..

New Releases

Recently Written

Others Went Here Next

Still Curious?

Thank you for reading about Array Push Key And Value Php. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home