Open In App

How to Push Both Key and Value into PHP Array ?

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
2 Likes
Like
Report

Given an array, the task is to push a new key and value pair into the array. There are some methods to push value and key into the PHP array, these are:

Approach 1: Using Square Bracket [] Syntax

A value can be directly assigned to a specific key by using the square bracket syntax.

Example:


Output
1 => GeeksforGeeks
2 => GFG
3 => Learn, Practice, and Excel
4 => PHP

Approach 2: Using array_merge() Function

The array_merge() function merges two arrays being passed as arguments. The first argument of the array_push() function is the original array and subsequent argument is the key and the value to be added to the array in the form of an array as well.

Note: Keep in mind that this method will re-number numeric keys, if any (keys will start from 0, 1, 2...).

Example:


Output
One => GeeksforGeeks
Two => GFG
Three => Learn, Practice, and Excel
Four => PHP

Approach 3: Using += Operator

The += operator can be used to append a key-value pair to the end of the array.

Example:


Output
1 => GeeksforGeeks
2 => GFG
3 => Learn, Practice, and Excel
4 => PHP

Approach 4: Using the array_combine Function

The array_combine function in PHP creates an associative array by combining two arrays: one for keys and one for values. Each element in the first array is used as a key, and the corresponding element in the second array becomes the value.

Example:


Output
Array
(
    [name] => Alice
    [age] => 25
    [city] => New York
)

Approach 5: Using array_replace()

In the array_replace() approach, you merge an existing array with a new array containing the key-value pair. This function replaces elements in the original array with elements from the new array. It adds the key-value pair if the key doesn't exist.

Example:


Output
Array
(
    [fruit] => apple
)

Approach 6: Using array_push() with Reference

This method involves using the array_push() function to add an associative array (containing the new key-value pair) to the original array. The array_push() function can add one or more elements to the end of an array.

Example: In this example, the pushKeyValuePair function takes the original array by reference, along with the key and value to be added. It creates an associative array containing the new key-value pair and then uses array_push() to add this associative array to the original array.


Output
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
    [0] => Array
        (
            [d] => 4
        )

)

Approach 7: Using array_splice()

The array_splice() function can be used to insert a new key-value pair into an array at a specific position. By specifying the position as the end of the array, this function can effectively add the new pair to the array.

Example:


Output
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

Similar Reads