Maps in PHP

Maps are PHP’s associative array, which allows you to index arrays with string keys.

To create an empty map, use an empty array.

<?php
// Create an empty associative array
$m = array();

Set key/value pairs using typical $array[key] = val syntax.

$m["k1"] = 7;
$m["k2"] = 13;

Printing the array with print_r will show all of its key/value pairs.

print_r($m);

Get a value for a key with $array[key].

$v1 = $m["k1"];
echo "v1: " . $v1 . "\n";

If the key doesn’t exist, null is returned in PHP.

$v3 = $m["k3"];
echo "v3: " . $v3 . "\n"; // Output will be blank since $v3 is null

The count function returns the number of key/value pairs when called on a map.

echo "len: " . count($m) . "\n";

The unset function removes key/value pairs from a map.

unset($m["k2"]);
print_r($m);

To remove all key/value pairs from a map, reassign it to an empty array.

$m = array();
print_r($m);

Check if a key exists in the map using array_key_exists.

$prs = array_key_exists("k2", $m);
echo "prs: " . ($prs ? 'true' : 'false') . "\n"; // Outputs: prs: false

You can also declare and initialize a new map in the same line with this syntax.

$n = array("foo" => 1, "bar" => 2);
print_r($n);

PHP doesn’t have a maps package like some other languages, but you can compare arrays directly.

$n2 = array("foo" => 1, "bar" => 2);
if ($n == $n2) {
    echo "n == n2";
}

Note that associative arrays appear in the form Array ( [k] => v [k] => v ) when printed with print_r.

array (
  'foo' => 1,
  'bar' => 2,
)

Example output when running the above code:

Array
(
    [k1] => 7
    [k2] => 13
)
v1: 7
v3: 
len: 2
Array
(
    [k1] => 7
)
Array
(
)
prs: false
Array
(
    [foo] => 1
    [bar] => 2
)
n == n2

Next example: Functions.