How to Push Both Key and Value into PHP Array ?
Last Updated :
05 Jan, 2024
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:
PHP
<?php
$myArray = [
"1" => "GeeksforGeeks" ,
"2" => "GFG" ,
"3" => "Learn, Practice, and Excel" ,
];
$myArray [ "4" ] = "PHP" ;
foreach ( $myArray as $keyName => $valueName ) {
echo $keyName . " => " . $valueName . "\n" ;
}
?>
|
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:
PHP
<?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" ;
}
?>
|
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:
PHP
<?php
$myArray = [
"1" => "GeeksforGeeks" ,
"2" => "GFG" ,
"3" => "Learn, Practice, and Excel" ,
];
$myArray += [ "4" => "PHP" ];
foreach ( $myArray as $keyName => $valueName ) {
echo $keyName . " => " . $valueName . "\n" ;
}
?>
|
Output
1 => GeeksforGeeks
2 => GFG
3 => Learn, Practice, and Excel
4 => PHP
Share your thoughts in the comments
Please Login to comment...