View Category

Define an empty map

php
$map = array();
$map = array("" => "");

Define an unmodifiable empty map

php
/* It's not possible to define an array as a constant
* Instead we can use the serialize-function */

$fruits = array("apple", "banana", "orange");
define("FRUITS", serialize($fruits));
echo FRUITS; // a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}
$my_fruits = unserialize(FRUITS); // and normal array again

Define an initial map

Define the map {circle:1, triangle:3, square:4}
php
$map = array("circle" => 1, "triangle" => 3, "square" => 4);

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
php
if (array_key_exists("mary", $pets)) {
echo "ok";
}
if (isset($pets["mary"])) { // only works if $pets["mary"] can't be false or 0
echo "ok";
}

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
php
echo $pets["joe"];

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
php
$pets["rob"] = "dog";

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
php
$last = array_pop($pets); // removes last key and assign it to the variable
echo $last;
$last = $pets[count($pets)-1];
echo $last;
unset($last);
$bill = $pets["bill"];
echo $bill;
unset($bill);
print_r(array_pop($pets));

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
php
$list = array("a","b","a","c","b","b");
$map = array_count_values($list);

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
php
foreach ($array as $m) {
$l = strlen($m);
$map[$l][] = $m;
}
arsort($map);