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.
Set key/value pairs using typical $array[key] = val
syntax.
Printing the array with print_r
will show all of its key/value pairs.
Get a value for a key with $array[key]
.
If the key doesn’t exist, null
is returned in PHP.
The count
function returns the number of key/value pairs when called on a map.
The unset
function removes key/value pairs from a map.
To remove all key/value pairs from a map, reassign it to an empty array.
Check if a key exists in the map using array_key_exists
.
You can also declare and initialize a new map in the same line with this syntax.
PHP doesn’t have a maps
package like some other languages, but you can compare arrays directly.
Note that associative arrays appear in the form Array ( [k] => v [k] => v )
when printed with print_r
.
Example output when running the above code:
Next example: Functions.