How to Push Both Key and Value into PHP Array ?
source link: https://www.geeksforgeeks.org/how-to-push-both-key-and-value-into-php-array/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to Push Both Key and Value into PHP Array ?
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 $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
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK