3

How to Push Both Key and Value into PHP Array ?

 4 months ago
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 ?

Courses

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";
}
?>
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
$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
$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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 05 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK