add a key-value pair to a map in php

To add a new key-value pair to a map (or associative array) in PHP, you can use the following syntax:

main.php
$myMap = array(
  "key1" => "value1",
  "key2" => "value2",
  "key3" => "value3"
);

$myMap["newKey"] = "newValue";
116 chars
8 lines

In this example, we have a map $myMap with three key-value pairs. To add a new key-value pair, we simply use the square bracket notation and assign a value to a new key, in this case "newKey" with the value "newValue".

We can then access the new key-value pair like any other in the map:

main.php
echo $myMap["newKey"]; // outputs "newValue"
45 chars
2 lines

Alternatively, we can also use the array_push() function to add a new key-value pair to the end of the map:

main.php
array_push($myMap, array("newKey" => "newValue"));
51 chars
2 lines

However, this is generally less common and not as efficient as assigning a new key-value pair directly with the square bracket notation.

gistlibby LogSnag