Map
Map allows you to use an array-like object which allows keys to be of any type as opposed to the
default integer or string types., (*1)
, (*2)
Installation
Install with:, (*3)
$ composer require carlosv2/map
Usage
To use Map you only need to create an instance of it and start using it as if it was an regular array:, (*4)
$foo = new Foo();
$map = new Map();
$map[$foo] = 'bar';
You can use any type you want as key. If you want, you can even mix them:, (*5)
$map = new Map();
$map[null] = 'null';
$map[[]] = 'array';
$map['string'] = 'string';
$map[1] = 'integer';
$map[true] = 'boolean';
$map[new \stdClass()] = 'object';
foreach ($map as $key => $value) {
var_dump($key, $value);
}
API
The following functions are available in the Map class., (*6)
has:
Checks whether a key exists or not:, (*7)
$obj = new \stdClass();
$map = new Map();
$map[$obj] = 'value';
$map->has($obj); // true
$map->has([]); // false
get:
Returns the value associated with the given key:, (*8)
$obj = new \stdClass();
$map = new Map();
$map[$obj] = 'value';
$map->get($obj); // 'value'
$map->get([]); // null
Optionally, a fallback value can be returned if the given key does not exist:, (*9)
$map = new Map();
$map->get([], 'default'); // 'default'
set:
Assigns the given value to the given key:, (*10)
$map = new Map();
$map->set($key, $value); // Equivalent to: $map[$key] = $value;
keys:
Returns the array of keys for that instance:, (*11)
$map = new Map();
$map[null] = 'null';
$map[[]] = 'array';
$map[true] = 'boolean';
$map->keys(); // [null, [], true]
values:
Returns the array of values for that instance:, (*12)
$map = new Map();
$map[null] = 'null';
$map[[]] = 'array';
$map[true] = 'boolean';
$map->values(); // ['null', 'array', 'boolean']
map:
Similar to array_map
but it returns another Map instance instead. The callable function may have the key as a
second argument:, (*13)
$map = new Map();
$map[null] = 'null';
$map[[]] = 'array';
$map[true] = 'boolean';
$newMap = $map->map(function ($value, $key) { return json_encode($key) . '_' . $value; });
$newMap->keys(); // [null, [], true]
$newMap->values(); // ['null_null', '[]_array', 'true_boolean']
Interfaces
The Map class implements the following interfaces:
- ArrayAccess
- Countable
- IteratorAggregate, (*14)