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:
Table of Content
Approach 1: Using Square Bracket [] Syntax
A value can be directly assigned to a specific key by using the square bracket syntax.
Example:
<?php $myArray = [
"1" => "GeeksforGeeks" ,
"2" => "GFG" ,
"3" => "Learn, Practice, and Excel" ,
]; $myArray [ "4" ] = "PHP" ;
foreach ( $myArray as $keyName => $valueName ) {
echo $keyName . " => " . $valueName . "\n" ;
} ?> |
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:
<?php $myArray = [
"One" => "GeeksforGeeks" ,
"Two" => "GFG" ,
"Three" => "Learn, Practice, and Excel" ,
]; $myArray = array_merge ( $myArray , [ "Four" => "PHP" ]);
foreach ( $myArray as $keyName => $valueName ) {
echo $keyName . " => " . $valueName . "\n" ;
} ?> |
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:
<?php $myArray = [
"1" => "GeeksforGeeks" ,
"2" => "GFG" ,
"3" => "Learn, Practice, and Excel" ,
]; $myArray += [ "4" => "PHP" ];
foreach ( $myArray as $keyName => $valueName ) {
echo $keyName . " => " . $valueName . "\n" ;
} ?> |
1 => GeeksforGeeks 2 => GFG 3 => Learn, Practice, and Excel 4 => PHP