How to Push Both Key and Value into PHP Array ?
Last Updated :
03 Jul, 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";
}
?>
Output1 => 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";
}
?>
OutputOne => 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";
}
?>
Output1 => 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:
PHP
<?php
// Define arrays for keys and values
$keys = ['name', 'age', 'city'];
$values = ['Alice', 25, 'New York'];
// Combine the two arrays into an associative array
$associativeArray = array_combine($keys, $values);
// Print the resulting array
print_r($associativeArray);
?>
OutputArray
(
[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:
PHP
<?php
$array = [];
$key = 'fruit';
$value = 'apple';
$array = array_replace($array, [$key => $value]);
print_r($array); // Output: Array ( [fruit] => apple )
?>
OutputArray
(
[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.
PHP
<?php
function pushKeyValuePair(&$array, $key, $value) {
// Create an associative array with the new key-value pair
$newElement = [$key => $value];
// Use array_push to add the associative array to the original array
array_push($array, $newElement);
}
// Example usage
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$key = 'd';
$value = 4;
pushKeyValuePair($array, $key, $value);
print_r($array);
?>
OutputArray
(
[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:
PHP
<?php
// Initialize the array
$array = ['a' => 1, 'b' => 2];
// Prepare the new key-value pair
$new_key_value = ['c' => 3];
// Convert the associative array to an indexed array for splicing
$keys = array_keys($array);
$values = array_values($array);
// Append the new key-value pair
array_splice($keys, count($keys), 0, array_keys($new_key_value));
array_splice($values, count($values), 0, array_values($new_key_value));
// Combine the keys and values back into an associative array
$array = array_combine($keys, $values);
print_r($array);
?>
OutputArray
(
[a] => 1
[b] => 2
[c] => 3
)
Similar Reads
How to search by multiple key => value in PHP array ?
In a multidimensional array, if there is no unique pair of key => value (more than one pair of key => value) exists then in that case if we search the element by a single key => value pair then it can return more than one item. Therefore we can implement the search with more than one key =
5 min read
How to get random value out of an array in PHP?
There are two functions to get random value out of an array in PHP. The shuffle() and array_rand() function is used to get random value out of an array.Examples: Input : $arr = ("a"=>"21", "b"=>"31", "c"=>"7", "d"=>"20") // Get one random value Output :7 Input : $arr = ("a"=>"21", "b"
3 min read
How to print all the values of an array in PHP ?
We have given an array containing some array elements and the task is to print all the values of an array arr in PHP. In order to do this task, we have the following approaches in PHP:Table of ContentUsing for-each loop: Using count() function and for loop: Using implode():Using print_r() FunctionUs
3 min read
How to remove a key and its value from an associative array in PHP ?
Given an associative array containing array elements the task is to remove a key and its value from the associative array. Examples: Input : array( "name" => "Anand", "roll"=> "1") Output : Array ( [roll] => 1 ) Input : array( "1" => "Add", "2" => "Multiply", "3" => "Divide") Outpu
2 min read
How to search by key=>value in a multidimensional array in PHP ?
In PHP, multidimensional array search refers to searching a key=>value in a multilevel nested array. This search can be done either by the iterative or recursive approach. Table of ContentRecursive ApproachIterative ApproachUsing array_filter() FunctionRecursive Approach:Check if the key exists i
4 min read
How to Sort Multi-Dimensional Array by Key Value in PHP?
Sorting a multi-dimensional array by key value in PHP can be useful in various scenarios, such as organizing data for display or processing. In this article, we will explore different approaches to achieve this.Table of ContentSort Multi-Dimensional Array using array_multisort() FunctionSort Multi-D
4 min read
How to merge arrays and preserve the keys in PHP ?
Arrays in PHP are created using array() function. Arrays are variable that can hold more than one values at a time. There are three types of arrays: Indexed Arrays Associative Arrays Multidimensional Arrays Each and every value in an array has a name or identity attached to it used to access that el
2 min read
How to re-index an array in PHP?
The re-index of an array can be done by using some inbuilt function together. These functions are: array_combine() Function: The array_combine() function is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values.
5 min read
How to convert an array into object using stdClass() in PHP?
To convert an array into the object, stdClass() is used. The stdClass() is an empty class, which is used to cast other types to object. If an object is converted to object, its not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is
3 min read
How to Check an Array Contains only Unique Values in PHP?
In PHP, verifying that an array contains unique values is a common task. This involves ensuring that each element in the array appears only once. There are multiple methods to achieve this check effectively:Table of ContentUsing array_unique () and count() functionUsing array_count_values() function
4 min read