3.5. Maps

Xyster_Collection_Map_Interface-based objects have keys instead of numbers like a list (although the keys could be numbers... they can be any value).

Xyster_Collection_Map_Interface objects implement ArrayAccess (defined in the PHP SPL), which means you can get items inside via array style.

// if $map is a Xyster_Collection_Map_Interface

echo 'Number of entries: ' . count($map) . "\n";

foreach( $map->keys() as $key ) {
        printf("key: %s, value: %s\n", $key, $map->get($key));

3.5.1. String Maps

These are also called hash tables and associative arrays. You can use a string map just like you would use a PHP array, except you can also treat it like an object.

if ( isset($map['test']) ) { // or $map->containsKey('test')
        echo $map['test'];

echo 'Find key for value: ' . $map->keyFor('search value');
echo 'Find all keys for value: ' . implode(', ', $map->keysFor('search value'));

$aliases = new Xyster_Collection_Map_String();
$aliases['batman'] = 'Bruce';
$aliases['wolverine'] = 'Logan';
$aliases['wonderwoman'] = 'Diana';
$aliases['gambit'] = 'Remy';

$more = new Xyster_Collection_Map_String();
$more['doom'] = 'Victor';
$more['spidey'] = 'Peter';
$more['shazam'] = 'Billy';


// to remove, use
// because is easier than

3.5.2. Object Maps

Maps with objects as keys are what you have in strongly-typed languages. In Java or .NET, for instance, everything is an object including strings and integers. Xyster_Collection_Map is the default implementation of this type of map. Note that PHP's ArrayAccess syntax doesn't work for objects as keys. Because of this, you are limited to using the get, set, remove, and containsKey methods only.

Using objects as keys is invaluable for preventing key collisions. Each object is used uniquely as a key, so two different instances of the same class with the same property values are two different keys.