W3docs

array_push() with key value pair

To add an element to the end of an array with a key-value pair in PHP, you can use the array_push() function.

To add key-value pairs to an array in PHP, the most reliable method is using the direct assignment syntax: $array['key'] = 'value'.

Adding key-value pairs to an array in PHP

php— editable, runs on the server

Output:

Array ( [apple] => red [banana] => yellow [mango] => orange [pear] => green )

Note that array_push() is designed for appending sequential values and cannot merge key-value pairs. When you pass an associative array to array_push(), PHP treats it as a single element and assigns it a numeric key, which nests the array instead of adding its pairs to the target array:

How array_push() handles associative arrays

php— editable, runs on the server

Output:

Array ( [apple] => red [banana] => yellow [0] => Array ( [mango] => orange [pear] => green ) )

If you only need to append values to the end of an array, array_push() works as expected:

Using array_push() for sequential values

php— editable, runs on the server

Output:

Array ( [0] => apple [1] => banana [2] => mango [3] => pear )

For merging existing associative arrays, consider array_merge() or the + operator instead.

Merging associative arrays with array_merge()

php— editable, runs on the server

Output:

Array ( [apple] => red [banana] => yellow [mango] => orange [pear] => green )