https://github.com/aimeos/map
PHP arrays and collections made easy
https://github.com/aimeos/map
array collection map php php-arrays php-map
Last synced: about 1 year ago
JSON representation
PHP arrays and collections made easy
- Host: GitHub
- URL: https://github.com/aimeos/map
- Owner: aimeos
- License: mit
- Created: 2019-11-18T03:35:21.000Z (over 6 years ago)
- Default Branch: 3.x
- Last Pushed: 2025-03-07T10:57:36.000Z (about 1 year ago)
- Last Synced: 2025-04-23T15:54:30.038Z (about 1 year ago)
- Topics: array, collection, map, php, php-arrays, php-map
- Language: PHP
- Homepage: http://php-map.org
- Size: 941 KB
- Stars: 3,594
- Watchers: 9
- Forks: 17
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# PHP arrays and collections made easy
Easy and elegant handling of PHP arrays by using an array-like collection object
as offered by jQuery and Laravel Collections.
```bash
composer req aimeos/map
```
Supported PHP versions:
* PHP 7.1+
* PHP 8+
**Table of contents**
* [Why PHP Map](#why-php-map)
* [List of methods](#methods)
* [Create](#create)
* [Access](#access)
* [Add](#add)
* [Aggregate](#aggregate)
* [Debug](#debug)
* [Order](#order-by)
* [Shorten](#shorten)
* [Test](#test)
* [Mutate](#mutate)
* [Misc](#misc)
* [Documentation](#method-documentation)
* [Custom methods](#custom-methods)
* [Performance](#performance)
* [Upgrade guide](#upgrade-guide)
## Why PHP Map
**Instead of:**
```php
$list = [['id' => 'one', 'value' => 'value1'], ['id' => 'two', 'value' => 'value2'], null];
$list[] = ['id' => 'three', 'value' => 'value3']; // add element
unset( $list[0] ); // remove element
$list = array_filter( $list ); // remove empty values
sort( $list ); // sort elements
$pairs = array_column( $list, 'value', 'id' ); // create ['three' => 'value3']
$value = reset( $pairs ) ?: null; // return first value
```
**Only use:**
```php
$list = [['id' => 'one', 'value' => 'value1'], ['id' => 'two', 'value' => 'value2'], null];
$value = map( $list ) // create Map
->push( ['id' => 'three', 'value' => 'value3'] ) // add element
->remove( 0 ) // remove element
->filter() // remove empty values
->sort() // sort elements
->col( 'value', 'id' ) // create ['three' => 'value3']
->first(); // return first value
```
**You can still use:**
```php
$map[] = ['id' => 'three', 'value' => 'value3'];
$value = $map[0];
count( $map );
foreach( $map as $key => value );
```
**Use callbacks:**
Also, the map object allows you to pass anonymous functions to a lot of methods, e.g.:
```php
$map->each( function( $val, $key ) {
echo $key . ': ' . $val;
} );
```
**jQuery style:**
If your map elements are objects, you can call their methods for each object and get
the result as new map just like in jQuery:
```php
// MyClass implements setStatus() (returning $this) and getCode() (initialized by constructor)
$map = Map::from( ['a' => new MyClass( 'x' ), 'b' => new MyClass( 'y' )] );
$map->setStatus( 1 )->getCode()->toArray();
```
This will call `setStatus( 1 )` on both objects. If `setStatus()` implementation
returns `$this`, the new map will also contain:
```php
['a' => MyClass(), 'b' => MyClass()]
```
On those new map elements, `getCode()` will be called which returns `x` for the
first object and `y` for the second. The map created from the results of `getCode()`
will return:
```php
['a' => 'x', 'b' => 'y']
```
## Methods
function is_map
function map
__construct
__call
__callStatic
after
all
any
arsort
arsorted
asort
asorted
at
avg
before
bool
call
cast
chunk
clear
clone
col
collapse
combine
concat
contains
copy
count
countBy
dd
delimiter
diff
diffAssoc
diffKeys
dump
duplicates
each
empty
equals
every
except
explode
fill
filter
find
findKey
first
firstKey
flat
flip
float
from
fromJson
get
getIterator
grep
groupBy
has
if
ifAny
ifEmpty
implements
in
includes
index
insertAfter
insertAt
insertBefore
int
intersect
intersectAssoc
intersectKeys
is
isEmpty
isList
isObject
isNumeric
isScalar
isString
join
jsonSerialize
keys
krsort
krsorted
ksort
ksorted
last
lastKey
ltrim
map
max
merge
method
min
none
nth
offsetExists
offsetGet
offsetSet
offsetUnset
only
order
pad
partition
percentage
pipe
pluck
pop
pos
prefix
prepend
pull
push
put
random
reduce
reject
rekey
remove
replace
reverse
reversed
rsort
rsorted
rtrim
search
sep
set
shift
shuffle
shuffled
skip
slice
some
sort
sorted
splice
strAfter
strBefore
strCompare
strContains
strContainsAll
strEnds
strEndsAll
string
strLower
strReplace
strStarts
strStartsAll
strUpper
suffix
sum
take
tap
times
to
toArray
toJson
toReversed
toSorted
toUrl
transform
transpose
traverse
tree
trim
uasort
uasorted
uksort
uksorted
union
unique
unshift
usort
usorted
values
walk
where
with
zip
### Create
* [function map()](#map-function) : Creates a new map from passed elements
* [__construct()](#__construct) : Creates a new map
* [clone()](#clone) : Clones the map and all objects within
* [copy()](#copy) : Creates a new copy
* [explode()](#explode) : Splits a string into a map of elements
* [fill()](#fill) : Creates a new map filled with given value
* [from()](#from) : Creates a new map from passed elements
* [fromJson()](#fromjson) : Creates a new map from a JSON string
* [times()](#times) : Creates a new map by invoking the closure a number of times
* [tree()](#tree) : Creates a tree structure from the list items
### Access
* [__call()](#__call) : Calls a custom method
* [__callStatic()](#__callstatic) : Calls a custom method statically
* [all()](#all) : Returns the plain array
* [any()](#any) : Tests if at least one element satisfies the callback function
* [at()](#at) : Returns the value at the given position
* [bool()](#bool) : Returns an element by key and casts it to boolean
* [call()](#call) : Calls the given method on all items
* [find()](#find) : Returns the first/last element where the callback returns TRUE
* [findKey()](#findkey) : Returns the first/last key where the callback returns TRUE
* [first()](#first) : Returns the first element
* [firstKey()](#firstkey) : Returns the first key
* [get()](#get) : Returns an element by key
* [index()](#index) : Returns the numerical index of the given key
* [int()](#int) : Returns an element by key and casts it to integer
* [float()](#float) : Returns an element by key and casts it to float
* [keys()](#keys) : Returns all keys
* [last()](#last) : Returns the last element
* [lastKey()](#lastkey) : Returns the last key
* [pop()](#pop) : Returns and removes the last element
* [pos()](#pos) : Returns the numerical index of the value
* [pull()](#pull) : Returns and removes an element by key
* [random()](#random) : Returns random elements preserving keys
* [search()](#search) : Find the key of an element
* [shift()](#shift) : Returns and removes the first element
* [string()](#string) : Returns an element by key and casts it to string
* [to()](#to) : Returns the plain array
* [toArray()](#toarray) : Returns the plain array
* [values()](#values) : Returns all elements with new keys
### Add
* [concat()](#concat) : Adds all elements with new keys
* [insertAfter()](#insertafter) : Inserts the value after the given element
* [insertAt()](#insertat) : Inserts the element at the given position in the map
* [insertBefore()](#insertbefore) : Inserts the value before the given element
* [merge()](#merge) : Combines elements overwriting existing ones
* [pad()](#pad) : Fill up to the specified length with the given value
* [prepend()](#prepend) : Adds an element at the beginning (alias)
* [push()](#push) : Adds an element to the end
* [put()](#put) : Sets the given key and value in the map (alias)
* [set()](#set) : Overwrites or adds an element
* [union()](#union) : Adds the elements without overwriting existing ones
* [unshift()](#unshift) : Adds an element at the beginning
* [with()](#with) : Returns a copy and sets an element
### Aggregate
* [avg()](#avg) : Returns the average of all values
* [count()](#count) : Returns the total number of elements
* [countBy()](#countby) : Counts how often the same values are in the map
* [max()](#max) : Returns the maximum value of all elements
* [min()](#min) : Returns the minium value of all elements
* [percentage()](#percentage) : Returns the percentage of all elements passing the test
* [sum()](#sum) : Returns the sum of all values in the map
### Debug
* [dd()](#dd) : Prints the map content and terminates the script
* [dump()](#dump) : Prints the map content
* [tap()](#tap) : Passes a clone of the map to the given callback
### Order By
* [arsort()](#arsort) : Reverse sort elements preserving keys
* [arsorted()](#arsorted) : Reverse sort elements preserving keys in a copy of the map
* [asort()](#asort) : Sort elements preserving keys
* [asorted()](#asorted) : Sort elements preserving keys in a copy of the map
* [krsort()](#krsort) : Reverse sort elements by keys
* [krsorted()](#krsorted) : Reverse sort elements by keys in a copy of the map
* [ksort()](#ksort) : Sort elements by keys
* [ksorted()](#ksorted) : Sorts a copy of the elements by their keys
* [order()](#order) : Orders elements by the passed keys
* [reverse()](#reverse) : Reverses the array order preserving keys
* [reversed()](#reversed) : Reverses the element order in a copy of the map
* [toReversed()](#toreversed) : Reverses the element order in a copy of the map (alias)
* [rsort()](#rsort) : Reverse sort elements using new keys
* [rsorted()](#rsorted) : Reverse sort elements using new keys in a copy of the map
* [shuffle()](#shuffle) : Randomizes the element order
* [shuffled()](#shuffled) : Randomizes the element order in a copy of the map
* [sort()](#sort) : Sorts the elements in-place assigning new keys
* [sorted()](#sorted) : Sorts the elements in a copy of the map using new keys
* [toSorted()](#tosorted) : Sorts the elements in a copy of the map using new keys (alias)
* [uasort()](#uasort) : Sorts elements preserving keys using callback
* [uasorted()](#uasorted) : Sorts elements preserving keys using callback in a copy of the map
* [uksort()](#uksort) : Sorts elements by keys using callback
* [uksorted()](#uksorted) : Sorts elements by keys using callback in a copy of the map
* [usort()](#usort) : Sorts elements using callback assigning new keys
* [usorted()](#usorted) : Sorts elements using callback assigning new keys in a copy of the map
### Shorten
* [after()](#after) : Returns the elements after the given one
* [before()](#before) : Returns the elements before the given one
* [clear()](#clear) : Removes all elements
* [diff()](#diff) : Returns the elements missing in the given list
* [diffAssoc()](#diffassoc) : Returns the elements missing in the given list and checks keys
* [diffKeys()](#diffkeys) : Returns the elements missing in the given list by keys
* [duplicates()](#duplicates) : Returns the duplicate values from the map
* [except()](#except) : Returns a new map without the passed element keys
* [filter()](#filter) : Applies a filter to all elements
* [grep()](#grep) : Applies a regular expression to all elements
* [intersect()](#intersect) : Returns the elements shared
* [intersectAssoc()](#intersectassoc) : Returns the elements shared and checks keys
* [intersectKeys()](#intersectkeys) : Returns the elements shared by keys
* [nth()](#nth) : Returns every nth element from the map
* [only()](#only) : Returns only those elements specified by the keys
* [pop()](#pop) : Returns and removes the last element
* [pull()](#pull) : Returns and removes an element by key
* [reject()](#reject) : Removes all matched elements
* [remove()](#remove) : Removes an element by key
* [shift()](#shift) : Returns and removes the first element
* [skip()](#skip) : Skips the given number of items and return the rest
* [slice()](#slice) : Returns a slice of the map
* [take()](#take) : Returns a new map with the given number of items
* [unique()](#unique) : Returns all unique elements preserving keys
* [where()](#where) : Filters the list of elements by a given condition
### Test
* [function is_map()](#is_map-function) : Tests if the variable is a map object
* [any()](#any) : Tests if at least one element satisfies the callback function
* [contains()](#contains) : Tests if an item exists in the map
* [each()](#each) : Applies a callback to each element
* [empty()](#empty) : Tests if map is empty
* [equals()](#equals) : Tests if map contents are equal
* [every()](#every) : Verifies that all elements pass the test of the given callback
* [has()](#has) : Tests if a key exists
* [if()](#if) : Executes callbacks depending on the condition
* [ifAny()](#ifany) : Executes callbacks if the map contains elements
* [ifEmpty()](#ifempty) : Executes callbacks if the map is empty
* [in()](#in) : Tests if element is included
* [includes()](#includes) : Tests if element is included
* [is()](#is) : Tests if the map consists of the same keys and values
* [isEmpty()](#isempty) : Tests if map is empty
* [isList()](#islist) : Checks if the map contains a list of subsequentially numbered keys
* [isNumeric()](#isnumeric) : Tests if all entries are numeric values
* [isObject()](#isobject) : Tests if all entries are objects
* [isScalar()](#isscalar) : Tests if all entries are scalar values.
* [isString()](#isstring) : Tests if all entries are string values.
* [implements()](#implements) : Tests if all entries are objects implementing the interface
* [none()](#none) : Tests if none of the elements are part of the map
* [some()](#some) : Tests if at least one element is included
* [strCompare()](#strcompare) : Compares the value against all map elements
* [strContains()](#strcontains) : Tests if at least one of the passed strings is part of at least one entry
* [strContainsAll()](#strcontainsall) : Tests if all of the entries contains one of the passed strings
* [strEnds()](#strends) : Tests if at least one of the entries ends with one of the passed strings
* [strEndsAll()](#strendsall) : Tests if all of the entries ends with at least one of the passed strings
* [strStarts()](#strstarts) : Tests if at least one of the entries starts with at least one of the passed strings
* [strStartsAll()](#strstartsall) : Tests if all of the entries starts with one of the passed strings
### Mutate
* [cast()](#cast) : Casts all entries to the passed type
* [chunk()](#chunk) : Splits the map into chunks
* [col()](#col) : Creates a key/value mapping
* [collapse()](#collapse) : Collapses multi-dimensional elements overwriting elements
* [combine()](#combine) : Combines the map elements as keys with the given values
* [flat()](#flat) : Flattens multi-dimensional elements without overwriting elements
* [flip()](#flip) : Exchanges keys with their values
* [groupBy()](#groupby) : Groups associative array elements or objects
* [join()](#join) : Returns concatenated elements as string with separator
* [ltrim()](#ltrim) : Removes the passed characters from the left of all strings
* [map()](#map) : Applies a callback to each element and returns the results
* [partition()](#partition) : Breaks the list into the given number of groups
* [pipe()](#pipe) : Applies a callback to the whole map
* [pluck()](#pluck) : Creates a key/value mapping (alias)
* [prefix()](#prefix) : Adds a prefix to each map entry
* [reduce()](#reduce) : Computes a single value from the map content
* [rekey()](#rekey) : Changes the keys according to the passed function
* [replace()](#replace) : Replaces elements recursively
* [rtrim()](#rtrim) : Removes the passed characters from the right of all strings
* [splice()](#splice) : Replaces a slice by new elements
* [strAfter()](#strafter) : Returns the strings after the passed value
* [strBefore()](#strbefore) : Returns the strings before the passed value
* [strLower()](#strlower) : Converts all alphabetic characters to lower case
* [strReplace()](#strreplace) : Replaces all occurrences of the search string with the replacement string
* [strUpper()](#strupper) : Converts all alphabetic characters to upper case
* [suffix()](#suffix) : Adds a suffix to each map entry
* [toJson()](#tojson) : Returns the elements in JSON format
* [toUrl()](#tourl) : Creates a HTTP query string
* [transform()](#transform) : Applies a callback to each element which creates new key/value pairs
* [transpose()](#transpose) : Exchanges rows and columns for a two dimensional map
* [traverse()](#traverse) : Traverses trees of nested items passing each item to the callback
* [trim()](#trim) : Removes the passed characters from the left/right of all strings
* [walk()](#walk) : Applies the given callback to all elements
* [zip()](#zip) : Merges the values of all arrays at the corresponding index
### Misc
* [delimiter()](#delimiter) : Sets or returns the seperator for paths to multi-dimensional arrays
* [getIterator()](#getiterator) : Returns an iterator for the elements
* [jsonSerialize()](#jsonserialize) : Specifies the data which should be serialized to JSON
* [method()](#method) : Registers a custom method
* [offsetExists()](#offsetexists) : Checks if the key exists
* [offsetGet()](#offsetget) : Returns an element by key
* [offsetSet()](#offsetset) : Overwrites an element
* [offsetUnset()](#offsetunset) : Removes an element by key
* [sep()](#sep) : Sets the seperator for paths to multi-dimensional arrays in the current map
## Method documentation
### is_map() function
Tests if the variable is a map object
```php
function is_map( $var ) : bool
```
* @param **mixed** `$var` Variable to test
**Examples:**
```php
is_map( new Map() );
// true
is_map( [] );
// false
```
### map() function
Returns a new map for the passed elements.
```php
function map( $elements = [] ) : \Aimeos\Map
```
* @param **mixed** `$elements` List of elements or single value
* @return **\Aimeos\Map** Map instance
**Examples:**
```php
// array
map( [] );
// null
map( null );
// scalar
map( 'a' );
// object
map( new \stdClass() );
// map object
map( new Map() );
// iterable object
map( new ArrayObject() );
// closure evaluated lazily
map( function() {
return [];
} );
```
**See also:**
* [rekey()](#rekey) - Changes the keys according to the passed function
* [transform()](#transform) - Creates new key/value pairs using the passed function and returns a new map for the result
### __construct()
Creates a new map object.
```php
public function __construct( $elements = [] )
```
* @param **mixed** `$elements` Single element, list of elements, Map object, iterable objects or iterators, everything else
**Examples:**
```php
// array
new Map( [] );
// null
new Map( null );
// scalar
new Map( 'a' );
// object
new Map( new \stdClass() );
// map object
new Map( new Map() );
// iterable object
new Map( new ArrayObject() );
// closure evaluated lazily
new Map( function() {
return [];
} );
```
### __call()
Handles dynamic calls to custom methods for the class.
```php
public function __call( string $name, array $params )
```
* @param **string** `$name` Method name
* @param **array<mixed>** `$params` List of parameters
* @return **mixed** Result from called function or new map with results from the element methods
Calls a custom method added by [Map::method()](#method). The called method
has access to the internal array by using `$this->items`.
**Examples:**
```php
Map::method( 'case', function( $case = CASE_LOWER ) {
return new self( array_change_key_case( $this->items, $case ) );
} );
Map::from( ['a' => 'bar'] )->case( CASE_UPPER );
// ['A' => 'bar']
```
This does also allow calling object methods if the items are objects:
```php
$item = new MyClass(); // with method setStatus() (returning $this) and getCode() implemented
Map::from( [$item, $item] )->setStatus( 1 )->getCode()->toArray();
```
This will call the `setStatus()` method of each element in the map and
use their return values to create a new map. On the new map, the `getCode()`
method is called for every element and its return values are also stored in a new
map. This last map is then returned and the map keys from the original map are
preserved in the returned map.
If the elements are not objects, they are skipped and if this applies to all
elements, an empty map is returned. In case the map contains objects of mixed
types and one of them doesn't implement the called method, an error will be thrown.
**See also:**
* [__callStatic()](#__callStatic) - Handles static calls to custom methods for the class
* [call()](#call) - Calls the given method on all items and returns the result
### __callStatic()
Handles static calls to custom methods for the class.
```php
public static function __callStatic( string $name, array $params )
```
* @param **string** `$name` Method name
* @param **array<mixed>** `$params` List of parameters
* @return **mixed** Result from called function or new map with results from the element methods
* @throws **\BadMethodCallException** If no method has been registered for that name
Calls a custom method added by [Map::method()](#method) statically. The called method
has no access to the internal array because no object is available.
**Examples:**
```php
Map::method( 'foo', function( $arg1, $arg2 ) {} );
Map::foo( $arg1, $arg2 );
```
**See also:**
* [__call()](#__call) - Handles dynamic calls to custom methods for the class
* [call()](#call) - Calls the given method on all items and returns the result
### after()
Returns the elements after the given one.
```php
public function after( $value ) : self
```
* @param **\Closure|int|string** `$value` Value or function with (item, key) parameters
* @return **self<int|string,mixed>** New map with the elements after the given one
The keys are preserved using this method.
**Examples:**
```php
Map::from( [0 => 'b', 1 => 'a'] )->after( 'b' );
// [1 => 'a']
Map::from( ['a' => 1, 'b' => 0] )->after( 1 );
// ['b' => 0]
Map::from( [0 => 'b', 1 => 'a'] )->after( 'c' );
// []
Map::from( ['a', 'c', 'b'] )->after( function( $item, $key ) {
return $item >= 'c';
} );
// [2 => 'b']
```
**See also:**
* [before()](#before) - Returns the elements before the given one
### all()
Returns the elements as a plain array.
```php
public function all() : array
```
* @return **array** Plain array
**Examples:**
```php
Map::from( ['a'] )->all();
// ['a']
```
This method is for compatibility to Laravel Collections. Use [`to()`](#to) instead if possible.
**See also:**
* [to()](#to) - Returns the elements as a plain array
* [toArray()](#toarray) - Returns the elements as a plain array
### any()
Tests if at least one element satisfies the callback function.
```php
public function any( \Closure $callback ) : bool
```
* @param \Closure $callback Anonymous function with (item, key) parameter
* @return bool TRUE if at least one element satisfies the callback function, FALSE if not
**Examples:**
```php
Map::from( ['a', 'b'] )->any( function( $item, $key ) {
return $item === 'a';
} );
// TRUE
Map::from( ['a', 'b'] )->any( function( $item, $key ) {
return !is_string( $item );
} );
// FALSE
```
**See also:**
* [some()](#some) - Tests if at least one element passes the test or is part of the map
* [every()](#every) - Verifies that all elements pass the test of the given callback
### arsort()
Sorts all elements in reverse order and maintains the key association.
```php
public function arsort( int $options = SORT_REGULAR ) : self
```
* @param **int** `$options` Sort options for `arsort()`
* @return **self<int|string,mixed>** Updated map for fluid interface
The keys are preserved using this method and no new map is created.
The `$options` parameter modifies how the values are compared. Possible parameter values are:
- SORT_REGULAR : compare elements normally (don't change types)
- SORT_NUMERIC : compare elements numerically
- SORT_STRING : compare elements as strings
- SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by `setlocale()`
- SORT_NATURAL : compare elements as strings using "natural ordering" like `natsort()`
- SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURAL|SORT_FLAG_CASE to sort strings case-insensitively
**Examples:**
```php
Map::from( ['b' => 0, 'a' => 1] )->arsort();
// ['a' => 1, 'b' => 0]
Map::from( ['a', 'b'] )->arsort();
// ['b', 'a']
Map::from( [0 => 'C', 1 => 'b'] )->arsort();
// [1 => 'b', 0 => 'C']
Map::from( [0 => 'C', 1 => 'b'] )->arsort( SORT_STRING|SORT_FLAG_CASE );
// [0 => 'C', 1 => 'b'] because 'C' -> 'c' and 'c' > 'b'
```
**See also:**
* [arsorted()](#arsorted) - Sorts a copy of all elements in reverse order and maintains the key association
### arsorted()
Sorts a copy of all elements in reverse order and maintains the key association.
```php
public function arsorted( int $options = SORT_REGULAR ) : self
```
* @param **int** `$options` Sort options for `arsort()`
* @return **self<int|string,mixed>** New map
The keys are preserved using this method and a new map is created.
The `$options` parameter modifies how the values are compared. Possible parameter values are:
- SORT_REGULAR : compare elements normally (don't change types)
- SORT_NUMERIC : compare elements numerically
- SORT_STRING : compare elements as strings
- SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by `setlocale()`
- SORT_NATURAL : compare elements as strings using "natural ordering" like `natsort()`
- SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURAL|SORT_FLAG_CASE to sort strings case-insensitively
**Examples:**
```php
Map::from( ['b' => 0, 'a' => 1] )->arsorted();
// ['a' => 1, 'b' => 0]
Map::from( ['a', 'b'] )->arsorted();
// ['b', 'a']
Map::from( [0 => 'C', 1 => 'b'] )->arsorted();
// [1 => 'b', 0 => 'C']
Map::from( [0 => 'C', 1 => 'b'] )->arsorted( SORT_STRING|SORT_FLAG_CASE );
// [0 => 'C', 1 => 'b'] because 'C' -> 'c' and 'c' > 'b'
```
**See also:**
* [arsort()](#arsort) - Sorts all elements in reverse order and maintains the key association
### asort()
Sorts all elements and maintains the key association.
```php
public function asort( int $options = SORT_REGULAR ) : self
```
* @param **int** `$options` Sort options for `asort()`
* @return **self<int|string,mixed>** Updated map for fluid interface
The keys are preserved using this method and no new map is created.
The parameter modifies how the values are compared. Possible parameter values are:
- SORT_REGULAR : compare elements normally (don't change types)
- SORT_NUMERIC : compare elements numerically
- SORT_STRING : compare elements as strings
- SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by `setlocale()`
- SORT_NATURAL : compare elements as strings using "natural ordering" like `natsort()`
- SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURAL|SORT_FLAG_CASE to sort strings case-insensitively
**Examples:**
```php
Map::from( ['a' => 1, 'b' => 0] )->asort();
// ['b' => 0, 'a' => 1]
Map::from( [0 => 'b', 1 => 'a'] )->asort();
// [1 => 'a', 0 => 'b']
Map::from( [0 => 'C', 1 => 'b'] )->asort();
// [0 => 'C', 1 => 'b'] because 'C' < 'b'
Map::from( [0 => 'C', 1 => 'b'] )->asort( SORT_STRING|SORT_FLAG_CASE );
// [1 => 'b', 0 => 'C'] because 'C' -> 'c' and 'c' > 'b'
```
**See also:**
* [asorted()](#asorted) - Sorts a copy of all elements and maintains the key association
### asorted()
Sorts a copy of all elements and maintains the key association.
```php
public function asorted( int $options = SORT_REGULAR ) : self
```
* @param **int** `$options` Sort options for `asort()`
* @return **self<int|string,mixed>** New map
The keys are preserved using this method and a new map is created.
The parameter modifies how the values are compared. Possible parameter values are:
- SORT_REGULAR : compare elements normally (don't change types)
- SORT_NUMERIC : compare elements numerically
- SORT_STRING : compare elements as strings
- SORT_LOCALE_STRING : compare elements as strings, based on the current locale or changed by `setlocale()`
- SORT_NATURAL : compare elements as strings using "natural ordering" like `natsort()`
- SORT_FLAG_CASE : use SORT_STRING|SORT_FLAG_CASE and SORT_NATURAL|SORT_FLAG_CASE to sort strings case-insensitively
**Examples:**
```php
Map::from( ['a' => 1, 'b' => 0] )->asorted();
// ['b' => 0, 'a' => 1]
Map::from( [0 => 'b', 1 => 'a'] )->asorted();
// [1 => 'a', 0 => 'b']
Map::from( [0 => 'C', 1 => 'b'] )->asorted();
// [0 => 'C', 1 => 'b'] because 'C' < 'b'
Map::from( [0 => 'C', 1 => 'b'] )->asorted( SORT_STRING|SORT_FLAG_CASE );
// [1 => 'b', 0 => 'C'] because 'C' -> 'c' and 'c' > 'b'
```
**See also:**
* [asort()](#asort) - Sorts all elements and maintains the key association
### at()
Returns the value at the given position.
```php
public function at( int $pos )
```
* @param **int** `$pos` Position of the value in the map
* @return **mixednull** Value at the given position or NULL if no value is available
The position starts from zero and a position of "0" returns the first element
of the map, "1" the second and so on. If the position is negative, the sequence
will start from the end of the map.
**Examples:**
```php
Map::from( [1, 3, 5] )->at( 0 );
// 1
Map::from( [1, 3, 5] )->at( 1 );
// 3
Map::from( [1, 3, 5] )->at( -1 );
// 5
Map::from( [1, 3, 5] )->at( 3 );
// NULL
```
**See also:**
* [index()](#index) - Returns the numerical index of the given key
* [pos()](#pos) - Returns the numerical index of the value
### avg()
Returns the average of all integer and float values in the map.
```php
public function avg( $col = null ) : float
```
* @param **Closure|string|null** `$col` Closure, key or path to the values in the nested array or object to compute the average for
* @return **float** Average of all elements or 0 if there are no elements in the map
Non-numeric values will be removed before calculation.
This does also work for multi-dimensional arrays by passing the keys
of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
to get "val" from `['key1' => ['key2' => ['key3' => 'val']]]`. The same applies to
public properties of objects or objects implementing `__isset()` and `__get()` methods.
**Examples:**
```php
Map::from( [1, 3, 5] )->avg();
// 3
Map::from( [1, null, 5] )->avg();
// 3
Map::from( [1, 'sum', 5] )->avg();
// 2
Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->avg( 'p' );
// 30
Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->avg( 'i/p' );
// 40
Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->avg( fn( $val, $key ) => $val['i']['p'] ?? null );
// 40
Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->avg( fn( $val, $key ) => $key < 1 ? $val : null );
// 30
```
**See also:**
* [count()](#count) - Returns the total number of elements
* [max()](#max) - Returns the maximum value of all elements
* [min()](#min) - Returns the minium value of all elements
* [percentage()](#percentage) - Returns the percentage of all elements passing the test
* [sum()](#sum) - Returns the sum of all values in the map
### before()
Returns the elements before the given one.
```php
public function before( $value ) : self
```
* @param **\Closure|int|string** `$value` Value or function with (item, key) parameters
* @return **self<int|string,mixed>** New map with the elements before the given one
The keys are preserved using this method.
**Examples:**
```php
Map::from( ['a' => 1, 'b' => 0] )->before( 0 );
// ['a' => 1]
Map::from( [0 => 'b', 1 => 'a'] )->before( 'a' );
// [0 => 'b']
Map::from( [0 => 'b', 1 => 'a'] )->before( 'c' );
// []
Map::from( ['a', 'c', 'b'] )->before( function( $item, $key ) {
return $key >= 1;
} );
// [0 => 'a']
```
**See also:**
* [after()](#after) - Returns the elements after the given one
### bool()
Returns an element by key and casts it to boolean if possible.
```php
public function bool( $key, $default = false ) : bool
```
* @param **int|string** `$key` Key or path to the requested item
* @param **mixed** `$default` Default value if key isn't found (will be casted to bool)
* @return **bool** Value from map or default value
This does also work to map values from multi-dimensional arrays by passing the keys
of the arrays separated by the delimiter ("/" by default), e.g. `key1/key2/key3`
to get `val` from `['key1' => ['key2' => ['key3' => 'val']]]`. The same applies to
public properties of objects or objects implementing `__isset()` and `__get()` methods.
**Examples:**
```php
Map::from( ['a' => true] )->bool( 'a' );
// true
Map::from( ['a' => '1'] )->bool( 'a' );
// true (casted to boolean)
Map::from( ['a' => 1.1] )->bool( 'a' );
// true (casted to boolean)
Map::from( ['a' => '10'] )->bool( 'a' );
// true (casted to boolean)
Map::from( ['a' => 'abc'] )->bool( 'a' );
// true (casted to boolean)
Map::from( ['a' => ['b' => ['c' => true]]] )->bool( 'a/b/c' );
// true
Map::from( [] )->bool( 'c', function() { return rand( 1, 2 ); } );
// true (value returned by closure is casted to boolean)
Map::from( [] )->bool( 'a', true );
// true (default value used)
Map::from( [] )->bool( 'a' );
// false
Map::from( ['b' => ''] )->bool( 'b' );
// false (casted to boolean)
Map::from( ['b' => null] )->bool( 'b' );
// false (null is not scalar)
Map::from( ['b' => [true]] )->bool( 'b' );
// false (arrays are not scalar)
Map::from( ['b' => '#resource'] )->bool( 'b' );
// false (resources are not scalar)
Map::from( ['b' => new \stdClass] )->bool( 'b' );
// false (objects are not scalar)
Map::from( [] )->bool( 'c', new \Exception( 'error' ) );
// throws exception
```
**See also:**
* [cast()](#cast) - Casts all entries to the passed type
* [float()](#float) - Returns an element by key and casts it to float if possible
* [get()](#get) - Returns an element from the map by key
* [int()](#int) - Returns an element by key and casts it to integer if possible
* [string()](#string) - Returns an element by key and casts it to string if possible
### call()
Calls the given method on all items and returns the result.
```php
public function call( string $name, array $params = [] ) : self
```
* @param **string** `$name` Method name
* @param **array<mixed>** `$params` List of parameters
* @return **self<int|string,mixed>** New map with results from all elements
This method can call methods on the map entries that are also implemented
by the map object itself and are therefore not reachable when using the
magic `__call()` method. If some entries are not objects, they will be skipped.
The keys from the original map are preserved in the returned in the new map.
**Examples:**
```php
$item = new MyClass( ['myprop' => 'val'] ); // implements methods get() and toArray()
Map::from( [$item, $item] )->call( 'get', ['myprop'] );
// ['val', 'val']
Map::from( [$item, $item] )->call( 'toArray' );
// [['myprop' => 'val'], ['myprop' => 'val']]
```
**See also:**
* [__call()](#__call) - Handles dynamic calls to custom methods for the class
* [__callStatic()](#__callStatic) - Handles static calls to custom methods for the class
### cast()
Casts all entries to the passed type.
```php
public function cast( string $type = 'string' ) : self
```
* @param **string** `$type` Type to cast the values to ("string", "bool", "int", "float", "array", "object")
* @return **self<int|string,mixed>** Updated map with casted elements
Casting arrays and objects to scalar values won't return anything useful!
**Examples:**
```php
Map::from( [true, 1, 1.0, 'yes'] )->cast();
// ['1', '1', '1.0', 'yes']
Map::from( [true, 1, 1.0, 'yes'] )->cast( 'bool' );
// [true, true, true, true]
Map::from( [true, 1, 1.0, 'yes'] )->cast( 'int' );
// [1, 1, 1, 0]
Map::from( [true, 1, 1.0, 'yes'] )->cast( 'float' );
// [1.0, 1.0, 1.0, 0.0]
Map::from( [new stdClass, new stdClass] )->cast( 'array' );
// [[], []]
Map::from( [[], []] )->cast( 'object' );
// [new stdClass, new stdClass]
```
**See also:**
* [bool()](#bool) - Returns an element by key and casts it to boolean if possible
* [int()](#int) - Returns an element by key and casts it to integer if possible
* [float()](#float) - Returns an element by key and casts it to float if possible
* [string()](#string) - Returns an element by key and casts it to string if possible
### chunk()
Chunks the map into arrays with the given number of elements.
```php
public function chunk( int $size, bool $preserve = false ) : self
```
* @param **int** `$size` Maximum size of the sub-arrays
* @param **bool** `$preserve` Preserve keys in new map
* @return **self<int|string,mixed>** New map with elements chunked in sub-arrays
* @throws **\InvalidArgumentException** If size is smaller than 1
The last chunk may contain less elements than the given number.
The sub-arrays of the returned map are plain PHP arrays. If you need Map
objects, then wrap them with [Map::from()](#from) when you iterate over the map.
**Examples:**
```php
Map::from( [0, 1, 2, 3, 4] )->chunk( 3 );
// [[0, 1, 2], [3, 4]]
Map::from( ['a' => 0, 'b' => 1, 'c' => 2] )->chunk( 2 );
// [['a' => 0, 'b' => 1], ['c' => 2]]
```
**See also:**
* [partition()](#partition) - Breaks the list into the given number of groups
### clear()
Removes all elements from the current map.
```php
public function clear() : self
```
* @return **self<int|string,mixed>** Updated map for fluid interface
**Examples:**
```php
Map::from( [0, 1] )->clear();
// internal : []
```
**See also:**
* [except()](#except) - Returns a new map without the passed element keys
* [only()](#only) - Returns only those elements specified by the keys
* [reject()](#reject) - Removes all matched elements
* [remove()](#remove) - Removes an element by key
### clone()
Clones the map and all objects within.
```php
public function clone() : self
```
* @return **self<int|string,mixed>** New map with cloned objects
The objects within the Map are NOT the same as before but new cloned objects.
This is different to [`copy()`](#copy), which doesn't clone the objects within.
The keys are preserved using this method.
**Examples:**
```php
Map::from( [new \stdClass, new \stdClass] )->clone();
// [new \stdClass, new \stdClass]
```
**See also:**
* [copy()](#copy) - Creates a new copy
### col()
Returns the values of a single column/property from an array of arrays or list of elements in a new map.
```php
public function col( string $valuecol = null, string $indexcol = null ) : self
```
* @param **string|null** `$valuecol` Name or path of the value property
* @param **string|null** `$indexcol` Name or path of the index property
* @return **self<int|string,mixed>** New map with mapped entries
If $indexcol is omitted, it's value is NULL or not set, the result will be indexed from 0-n.
Items with the same value for $indexcol will overwrite previous items and only the last one
will be part of the resulting map.
This does also work to map values from multi-dimensional arrays by passing the keys
of the arrays separated by the delimiter ("/" by default), e.g. `key1/key2/key3`
to get `val` from `['key1' => ['key2' => ['key3' => 'val']]]`. The same applies to
public properties of objects or objects implementing `__isset()` and `__get()` methods.
**Examples:**
```php
Map::from( [['id' => 'i1', 'val' => 'v1'], ['id' => 'i2', 'val' => 'v2']] )->col( 'val' );
// ['v1', 'v2']
Map::from( [['id' => 'i1', 'val' => 'v1'], ['id' => 'i2', 'val' => 'v2']] )->col( 'val', 'id' );
// ['i1' => 'v1', 'i2' => 'v2']
Map::from( [['id' => 'i1', 'val' => 'v1'], ['id' => 'i2', 'val' => 'v2']] )->col( null, 'id' );
// ['i1' => ['id' => 'i1', 'val' => 'v1'], 'i2' => ['id' => 'i2', 'val' => 'v2']]
Map::from( [['id' => 'ix', 'val' => 'v1'], ['id' => 'ix', 'val' => 'v2']] )->col( null, 'id' );
// ['ix' => ['id' => 'ix', 'val' => 'v2']]
Map::from( [['foo' => ['bar' => 'one', 'baz' => 'two']]] )->col( 'foo/baz', 'foo/bar' );
// ['one' => 'two']
Map::from( [['foo' => ['bar' => 'one']]] )->col( 'foo/baz', 'foo/bar' );
// ['one' => null]
Map::from( [['foo' => ['baz' => 'two']]] )->col( 'foo/baz', 'foo/bar' );
// ['two']
```
**See also:**
* [map()](#map) - Applies a callback to each element and returns the results
* [pluck()](#pluck) - Creates a key/value mapping (alias)
* [rekey()](#pluck) - Changes the keys according to the passed function
### collapse()
Collapses all sub-array elements recursively to a new map.
```php
public function collapse( int $depth = null ) : self
```
* @param **int|null** `$depth` Number of levels to collapse for multi-dimensional arrays or NULL for all
* @return **self<int|string,mixed>** New map with all sub-array elements added into it recursively, up to the specified depth
The keys are preserved and already existing elements will be overwritten. This
is also true for numeric keys! This method is similar than [flat()](#flat) but replaces
already existing elements.
A value smaller than 1 for depth will return the same map elements. Collapsing
does also work if elements implement the "Traversable" interface (which the Map
object does).
**Examples:**
```php
Map::from( [0 => ['a' => 0, 'b' => 1], 1 => ['c' => 2, 'd' => 3]] )->collapse();
// ['a' => 0, 'b' => 1, 'c' => 2, 'd' => 3]
Map::from( [0 => ['a' => 0, 'b' => 1], 1 => ['a' => 2]] )->collapse();
// ['a' => 2, 'b' => 1]
Map::from( [0 => [0 => 0, 1 => 1], 1 => [0 => ['a' => 2, 0 => 3], 1 => 4]] )->collapse();
// [0 => 3, 1 => 4, 'a' => 2]
Map::from( [0 => [0 => 0, 'a' => 1], 1 => [0 => ['b' => 2, 0 => 3], 1 => 4]] )->collapse( 1 );
// [0 => ['b' => 2, 0 => 3], 1 => 4, 'a' => 1]
Map::from( [0 => [0 => 0, 'a' => 1], 1 => Map::from( [0 => ['b' => 2, 0 => 3], 1 => 4] )] )->collapse();
// [0 => 3, 'a' => 1, 'b' => 2, 1 => 4]
```
**See also:**
* [flat()](#flat) - Flattens multi-dimensional elements without overwriting elements
### combine()
Combines the values of the map as keys with the passed elements as values.
```php
public function combine( iterable $values ) : self
```
* @param **iterable<int|string,mixed>** `$values` Values of the new map
* @return **self<int|string,mixed>** New map
**Examples:**
```php
Map::from( ['name', 'age'] )->combine( ['Tom', 29] );
// ['name' => 'Tom', 'age' => 29]
```
**See also:**
* [zip()](#zip) - Merges the values of all arrays at the corresponding index
### concat()
Pushs all of the given elements onto the map without creating a new map.
```php
public function concat( iterable $elements ) : self
```
* @param **iterable<int|string,mixed>** `$elements` List of elements
* @return **self<int|string,mixed>** Updated map for fluid interface
The keys of the passed elements are NOT preserved!
**Examples:**
```php
Map::from( ['foo'] )->concat( ['bar'] );
// ['foo', 'bar']
Map::from( ['foo'] )->concat( new Map( ['bar' => 'baz'] ) );
// ['foo', 'baz']
```
**See also:**
* [merge()](#merge) - Merges the map with the given elements without returning a new map
* [union()](#union) - Builds a union of the elements and the given elements without returning a new map
### contains()
Determines if an item exists in the map.
```php
public function contains( $key, string $operator = null, $value = null ) : bool
```
This method combines the power of the `where()` method with `some()` to check
if the map contains at least one of the passed values or conditions.
* @param **\Closure|iterable|mixed** `$values` Anonymous function with (item, key) parameter, element or list of elements to test against
* @param **string|null** `$op` Operator used for comparison
* @param **mixed** `$value` Value used for comparison
* @return **bool** TRUE if at least one element is available in map, FALSE if the map contains none of them
Check the [`where()`](#where)] method for available operators.
**Examples:**
```php
Map::from( ['a', 'b'] )->contains( 'a' );
// true
Map::from( ['a', 'b'] )->contains( ['a', 'c'] );
// true
Map::from( ['a', 'b'] )->contains( function( $item, $key ) {
return $item === 'a'
} );
// true
Map::from( [['type' => 'name']] )->contains( 'type', 'name' );
// true
Map::from( [['type' => 'name']] )->contains( 'type', '!=', 'name' );
// false
```
**See also:**
* [in()](#in) - Tests if element is included
* [includes()](#includes) - Tests if element is included
* [where()](#where) - Filters the list of elements by a given condition
### copy()
Creates a new map with the same elements.
```php
public function copy() : self
```
* @return **self<int|string,mixed>** New map
Both maps share the same array until one of the map objects modifies the
array. Then, the array is copied and the copy is modfied (copy on write).
**Examples:**
```php
$m = Map::from( ['foo', 'bar'] );
$m2 = $m->copy();
// internal: ['foo', 'bar'] both two maps
```
**See also:**
* [clone()](#clone) - Clones the map and all objects within
### count()
Counts the number of elements in the map.
```php
public function count() : int
```
* @return **int** Number of elements
**Examples:**
```php
Map::from( ['foo', 'bar'] )->count();
// 2
```
**See also:**
* [avg()](#avg) - Returns the average of all integer and float values in the map
* [countBy()](#countby) - Counts how often the same values are in the map
* [max()](#max) - Returns the maximum value of all elements
* [min()](#min) - Returns the minium value of all elements
* [percentage()](#percentage) - Returns the percentage of all elements passing the test
* [sum()](#sum) - Returns the sum of all values in the map
### countBy()
Counts how often the same values are in the map.
```php
public function countBy( $col = null ) : self
```
* @param **\Closure|string|null** `$col` Key as "key1/key2/key3" or closure with (value, key) parameters returning the values for counting
* @return **self<int|string,mixed>** New map with values as keys and their count as value
This does also work for multi-dimensional arrays by passing the keys
of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
public properties of objects or objects implementing __isset() and __get() methods.
**Examples:**
```php
Map::from( [1, 'foo', 2, 'foo', 1] )->countBy();
// [1 => 2, 'foo' => 2, 2 => 1]
Map::from( [1.11, 3.33, 3.33, 9.99] )->countBy();
// ['1.11' => 1, '3.33' => 2, '9.99' => 1]
Map::from( [['i' => ['p' => 1.11]], ['i' => ['p' => 3.33]], ['i' => ['p' => 3.33]]] )->countBy( 'i/p' );
// ['1.11' => 1, '3.33' => 2]
Map::from( ['a@gmail.com', 'b@yahoo.com', 'c@gmail.com'] )->countBy( function( $email ) {
return substr( strrchr( $email, '@' ), 1 );
} );
// ['gmail.com' => 2, 'yahoo.com' => 1]
```
**See also:**
* [avg()](#avg) - Returns the average of all integer and float values in the map
* [groupBy()](#groupby) - Groups associative array elements or objects by the passed key or closure
* [max()](#max) - Returns the maximum value of all elements
* [min()](#min) - Returns the minium value of all elements
* [percentage()](#percentage) - Returns the percentage of all elements passing the test
* [sum()](#sum) - Returns the sum of all values in the map
### dd()
Dumps the map content and terminates the script.
```php
public function dd( callable $callback = null ) : void
```
* @param **callable|null** `$callback` Function receiving the map elements as parameter (optional)
The `dd()` method is very helpful to see what are the map elements passed
between two map methods in a method call chain. It stops execution of the
script afterwards to avoid further output.
**Examples:**
```php
Map::from( ['a' => 'foo', 'b' => 'bar'] )->sort()->dd()->first();
/*
Array
(
[0] => bar
[1] => foo
)
*/
```
The `first()` method isn't executed at all.
### delimiter()
Sets or returns the seperator for paths to values in multi-dimensional arrays or objects.
```php
public static function delimiter( ?string $char = null ) : string
```
* @param **string** `$char` Separator character, e.g. "." for "key.to.value" instaed of "key/to/value"
* @return **string** Separator used up to now
The static method only changes the separator for new maps created afterwards.
Already existing maps will continue to use the previous separator. To change
the separator of an existing map, use the [sep()](#sep) method instead.
**Examples:**
```php
Map::delimiter( '.' );
// '/'
Map::from( ['foo' => ['bar' => 'baz']] )->get( 'foo.bar' );
// 'baz'
```
**See also:**
* [sep()](#sep) - Sets the seperator for paths to values in multi-dimensional arrays or objects
### diff()
Returns the keys/values in the map whose values are not present in the passed elements in a new map.
```php
public function diff( iterable $elements, callable $callback = null ) : self
```
* @param **iterable<int|string,mixed>** `$elements` List of elements
* @param **callable|null** `$callback` Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
* @return **self<int|string,mixed>** New map
**Examples:**
```php
Map::from( ['a' => 'foo', 'b' => 'bar'] )->diff( ['bar'] );
// ['a' => 'foo']
```
If a callback is passed, the given function will be used to compare the values.
The function must accept two parameters (value A and B) and must return
-1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
greater than value B. Both, a method name and an anonymous function can be passed:
```php
Map::from( [0 => 'a'] )->diff( [0 => 'A'], 'strcasecmp' );
// []
Map::from( ['b' => 'a'] )->diff( ['B' => 'A'], 'strcasecmp' );
// []
Map::from( ['b' => 'a'] )->diff( ['c' => 'A'], function( $valA, $valB ) {
return strtolower( $valA ) <=> strtolower( $valB );
} );
// []
```
All examples will return an empty map because both contain the same values
when compared case insensitive.
The keys are preserved using this method.
**See also:**
* [diffAssoc()](#diffassoc) - Returns the keys/values in the map whose keys AND values are not present in the passed elements in a new map
* [diffKeys()](#diffkeys) - Returns the elements missing in the given list by keys
### diffAssoc()
Returns the keys/values in the map whose keys AND values are not present in the passed elements in a new map.
```php
public function diffAssoc( iterable $elements, callable $callback = null ) : self
```
* @param **iterable<int|string,mixed>** `$elements` List of elements
* @param **callable|null** `$callback` Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
* @return **self<int|string,mixed>** New map
**Examples:**
```php
Map::from( ['a' => 'foo', 'b' => 'bar'] )->diffAssoc( new Map( ['foo', 'b' => 'bar'] ) );
// ['a' => 'foo']
```
If a callback is passed, the given function will be used to compare the values.
The function must accept two parameters (valA, valB) and must return
-1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
greater than value B. Both, a method name and an anonymous function can be passed:
```php
Map::from( [0 => 'a'] )->diffAssoc( [0 => 'A'], 'strcasecmp' );
// []
Map::from( ['b' => 'a'] )->diffAssoc( ['B' => 'A'], 'strcasecmp' );
// []
Map::from( ['b' => 'a'] )->diffAssoc( ['c' => 'A'], function( $valA, $valB ) {
return strtolower( $valA ) <=> strtolower( $valB );
} );
// ['b' => 'a']
```
The first and second example will return an empty map because both contain the
same values when compared case insensitive. In the third example, the keys doesn't
match ("b" vs. "c").
The keys are preserved using this method.
**See also:**
* [diff()](#diff) - Returns the keys/values in the map whose values are not present in the passed elements in a new map
a new map
* [diffKeys()](#diffkeys) - Returns the elements missing in the given list by keys
### diffKeys()
Returns the key/value pairs from the map whose keys are not present in the passed elements in a new map.
```php
public function diffKeys( iterable $elements, callable $callback = null ) : self
```
* @param **iterable<int|string,mixed>** `$elements` List of elements
* @param **callable|null** `$callback` Function with (keyA, keyB) parameters and returns -1 (<), 0 (=) and 1 (>)
* @return **self<int|string,mixed>** New map
**Examples:**
```php
Map::from( ['a' => 'foo', 'b' => 'bar'] )->diffKeys( new Map( ['foo', 'b' => 'baz'] ) );
// ['a' => 'foo']
```
If a callback is passed, the given function will be used to compare the keys.
The function must accept two parameters (key A and B) and must return
-1 if key A is smaller than key B, 0 if both are equal and 1 if key A is
greater than key B. Both, a method name and an anonymous function can be passed:
```php
Map::from( [0 => 'a'] )->diffKeys( [0 => 'A'], 'strcasecmp' );
// []
Map::from( ['b' => 'a'] )->diffKeys( ['B' => 'X'], 'strcasecmp' );
// []
Map::from( ['b' => 'a'] )->diffKeys( ['c' => 'a'], function( $keyA, $keyB ) {
return strtolower( $keyA ) <=> strtolower( $keyB );
} );
// ['b' => 'a']
```
The first and second example will return an empty map because both contain
the same keys when compared case insensitive. The third example will return
['b' => 'a'] because the keys doesn't match ("b" vs. "c").
The keys are preserved using this method.
**See also:**
* [diff()](#diff) - Returns the keys/values in the map whose values are not present in the passed elements in a new map
* [diffAssoc()](#diffassoc) - Returns the keys/values in the map whose keys AND values are not present in the passed elements in a new map
### dump()
Dumps the map content using the given function (print_r by default).
```php
public function dump( callable $callback = null ) : self
```
* @param **callable|null** `$callback` Function receiving the map elements as parameter (optional)
* @return **self<int|string,mixed>** Same map for fluid interface
The `dump()` method is very helpful to see what are the map elements passed
between two map methods in a method call chain.
**Examples:**
```php
Map::from( ['a' => 'foo', 'b' => 'bar'] )->dump()->asort()->dump( 'var_dump' );
/*
Array
(
[a] => foo
[b] => bar
)
array(1) {
["b"]=>
string(3) "bar"
["a"]=>
string(3) "foo"
}
*/
```
### duplicates()
Returns the duplicate values from the map.
```php
public function duplicates( $col = null ) : self
```
* @param **\Closure|string|null** `$col` Key, path of the nested array or anonymous function with ($item, $key) parameters returning the value for comparison
* @return **self<int|string,mixed>** New map
For nested arrays, you have to pass the name of the column of the nested array which
should be used to check for duplicates.
This does also work to map values from multi-dimensional arrays by passing the keys
of the arrays separated by the delimiter ("/" by default), e.g. `key1/key2/key3`
to get `val` from `['key1' => ['key2' => ['key3' => 'val']]]`. The same applies to
public properties of objects or objects implementing `__isset()` and `__get()` methods.
The keys in the result map are preserved.
**Examples:**
```php
Map::from( [1, 2, '1', 3] )->duplicates()
// [2 => '1']
Map::from( [['p' => '1'], ['p' => 1], ['p' => 2]] )->duplicates( 'p' )
// [1 => ['p' => 1]]
Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->duplicates( 'i/p' )
// [1 => ['i' => ['p' => 1]]]
Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->unique( fn( $item, $key ) => $item['i']['p'] );
// [1 => ['i' => ['p' => 1]]]
```
**See also:**
* [reject()](#reject) - Removes all matched elements
* [unique()](#unique) - Returns only unique elements from the map in a new map
### each()
Executes a callback over each entry until FALSE is returned.
```php
public function each( \Closure $callback ) : self
```
* @param **\Closure** `$callback` Function with (value, key) parameters and returns TRUE/FALSE
* @return **self<int|string,mixed>** Same map for fluid interface
**Examples:**
```php
$result = [];
Map::from( [0 => 'a', 1 => 'b'] )->each( function( $value, $key ) use ( &$result ) {
$result[$key] = strtoupper( $value );
return false;
} );
// $result = [0 => 'A']
```
The `$result` array will contain `[0 => 'A']` because FALSE is returned
after the first entry and all other entries are then skipped.
### empty()
Determines if the map is empty or not.
```php
public function empty() : bool
```
* @return **bool** TRUE if map is empty, FALSE if not
The method is equivalent to isEmpty().
**Examples:**
```php
Map::from( [] )->empty();
// true
Map::from( ['a'] )->empty();
// false
```
**See also:**
* [isEmpty()](#isempty) - Determines if the map is empty or not
### equals()
Tests if the passed elements are equal to the elements in the map.
```php
public function equals( iterable $elements ) : bool
```
* @param **iterable<int|string,mixed>** `$elements` List of elements to test against
* @return **bool** TRUE if both are equal, FALSE if not
The method differs to [is()](#is) in the fact that it doesn't care about the keys
by default. The elements are only loosely compared and the keys are ignored.
Values are compared by their string values:
```php
(string) $item1 === (string) $item2
```
**Examples:**
```php
Map::from( ['a'] )->equals( ['a', 'b'] );
// false
Map::from( ['a', 'b'] )->equals( ['b'] );
// false
Map::from( ['a', 'b'] )->equals( ['b', 'a'] );
// true
```
**See also:**
* [is()](#is) - Tests if the map consists of the same keys and values
### every()
Verifies that all elements pass the test of the given callback.
```php
public function every( \Closure $callback ) : bool
```
* @param **\Closure** `$callback` Function with (value, key) parameters and returns TRUE/FALSE
* @return **bool** True if all elements pass the test, false if if fails for at least one element
**Examples:**
```php
Map::from( [0 => 'a', 1 => 'b'] )->every( function( $value, $key ) {
return is_string( $value );
} );
// true
Map::from( [0 => 'a', 1 => 100] )->every( function( $value, $key ) {
return is_string( $value );
} );
// false
```
**See also:**
* [some()](#some) - Tests if at least one element passes the test or is part of the map
* [any()](#any) - Tests if at least one element satisfies the callback function
### except()
Returns a new map without the passed element keys.
```php
public function except( $keys ) : self
```
* @param **iterable<int|string>|array<int|string>|string|int** `$keys` List of keys to remove
* @return **self<int|string,mixed>** New map
The keys in the result map are preserved.
**Examples:**
```php
Map::from( ['a' => 1, 'b' => 2, 'c' => 3] )->except( 'b' );
// ['a' => 1, 'c' => 3]
Map::from( [1 => 'a', 2 => 'b', 3 => 'c'] )->except( [1, 3] );
// [2 => 'b']
```
**See also:**
* [clear()](#clear) - Removes all elements from the current map
* [only()](#only) - Returns only those elements specified by the keys
* [reject()](#reject) - Removes all matched elements
* [remove()](#remove) - Removes an element by key
### explode()
Creates a new map with the string splitted by the delimiter.
```php
public static function explode( string $delimiter , string $string , int $limit = PHP_INT_MAX ) : self
```
* @param **string** `$delimiter` Delimiter character, string or empty string
* @param **string** `$string` String to split
* @param **int** `$limit` Maximum number of element with the last element containing the rest of the string
* @return **self<int|string,mixed>** New map with splitted parts
A limit of "0" is treated the same as "1". If limit is negative, the rest of
the string is dropped and not part of the returned map.
This method creates a lazy Map and the string is split after calling
another method that operates on the Map contents.
**Examples:**
```php
Map::explode( ',', 'a,b,c' );
// ['a', 'b', 'c']
Map::explode( '<-->', 'a a<-->b b<-->c c' );
// ['a a', 'b b', 'c c']
Map::explode( '', 'string' );
// ['s', 't', 'r', 'i', 'n', 'g']
Map::explode( '|', 'a|b|c', 2 );
// ['a', 'b|c']
Map::explode( '', 'string', 2 );
// ['s', 't', 'ring']
Map::explode( '|', 'a|b|c|d', -2 );
// ['a', 'b']
Map::explode( '', 'string', -3 );
// ['s', 't', 'r']
```
### fill()
Creates a new map filled with given value.
```php
public static function fill( int $num, $value, int $start = 0 ) : self
```
* @param **int** `$num` Number of elements to create
* @param **mixed** `$value` Value to fill the map with
* @param **int** `$start` Start index for the elements
* @return **self<int|string,mixed>** New map with filled elements
**Examples:**
```php
Map::fill( 3, 'a' );
// [0 => 'a', 1 => 'a', 2 => 'a']
Map::fill( 3, 'a', 2 );
// [2 => 'a', 3 => 'a', 4 => 'a']
Map::fill( 3, 'a', -2 );
// [-2 => 'a', -1 => 'a', 0 => 'a'] (PHP 8)
// [-2 => 'a', 0 => 'a', 1 => 'a'] (PHP 7)
```
### filter()
Runs a filter over each element of the map and returns a new map.
```php
public function filter( callable $callback = null ) : self
```
* @param **callable|null** `$callback` Function with (item, key) parameters and returns TRUE/FALSE
* @return **self<int|string,mixed>** New map
If no callback is passed, all values which are empty, null or false will be
removed if their value converted to boolean is FALSE:
```php
(bool) $value === false
```
The keys in the result map are preserved.
**Examples:**
```php
Map::from( [null, 0, 1, '', '0', 'a'] )->filter();
// [1, 'a']
Map::from( [2 => 'a', 6 => 'b', 13 => 'm', 30 => 'z'] )->filter( function( $value, $key ) {
return $key < 10 && $value < 'n';
} );
// ['a', 'b']
```
**See also:**
* [grep()](#grep) - Applies a regular expression to all elements
* [where()](#where) - Filters the list of elements by a given condition
### find()
Returns the first matching element where the callback returns TRUE.
```php
public function find( \Closure $callback, $default = null, bool $reverse = false )
```
* @param **\Closure** `$callback` Function with (value, key) parameters and returns TRUE/FALSE
* @param **mixed** `$default` Default value, closure or exception if the callback only returns FALSE
* @param **bool** `$reverse` TRUE to test elements from back to front, FALSE for front to back (default)
* @return **mixed|null** First matching value, passed default value or an exception
**Examples:**
```php
Map::from( ['a', 'c', 'e'] )->find( function( $value, $key ) {
return $value >= 'b';
} );
// 'c'
Map::from( ['a', 'c', 'e'] )->find( function( $value, $key ) {
return $value >= 'b';
}, null, true );
// 'e' because $reverse = true
Map::from( [] )->find( function( $value, $key ) {
return $value >= 'b';
}, 'none' );
// 'none'
Map::from( [] )->find( function( $value, $key ) {
return $value >= 'b';
}, fn() => 'none' );
// 'none'
Map::from( [] )->find( function( $value, $key ) {
return $value >= 'b';
}, new \Exception( 'error' ) );
// throws \Exception
```
**See also:**
* [findKey()](#findkey) - Returns the first matching key where the callback returns TRUE
### findKey()
Returns the first matching key where the callback returns TRUE.
```php
public function findKey( \Closure $callback, $default = null, bool $reverse = false )
```
* @param **\Closure** `$callback` Function with (value, key) parameters and returns TRUE/FALSE
* @param **mixed** `$default` Default value, closure or exception if the callback only returns FALSE
* @param **bool** `$reverse` TRUE to test elements from back to front, FALSE for front to back (default)
* @return **mixed|null** First matching value, passed default value or an exception
**Examples:**
```php
Map::from( ['a', 'c', 'e'] )->findKey( function( $value, $key ) {
return $value >= 'b';
} );
// 1 because array has keys 0, 1 and 2
Map::from( ['a', 'c', 'e'] )->findKey( function( $value, $key ) {
return $value >= 'b';
}, null, true );
// 2 because array is reversed and 'e' >= 'b'
Map::from( [] )->findKey( function( $value, $key ) {
return $value >= 'b';
}, fn() => 'none' );
// default value 'none'
Map::from( [] )->findKey( function( $value, $key ) {
return $value >= 'b';
}, new \Exception( 'error' ) );
// throws exception
```
**See also:**
* [find()](#find) - Returns the first matching element where the callback returns TRUE
### first()
Returns the first element from the map.
```php
public function first( $default = null )
```
* @param **mixed** `$default` Default value, closure or exception if the map contains no elements
* @return **mixed** First value of map, (generated) default value or an exception
Using this method doesn't affect the internal array pointer.
**Examples:**
```php
Map::from( ['a', 'b'] )->first();
// 'a'
Map::from( [] )->first( 'x' );
// 'x'
Map::from( [] )->first( new \Exception( 'error' ) );
// throws \Exception
Map::from( [] )->first( function() { return rand(); } );
// random integer
```
**See also:**
* [firstKey()](#firstkey) - Returns the key of the first element from the map
* [last()](#last) - Returns the last element from the map
* [lastKey()](#lastkey) - Returns the key of the last element from the map
### firstKey()
Returns the key of the first element from the map.
```php
public function firstKey( $default = null )
```
* @param **mixed** `$default` Default value, closure or exception if the map contains no elements
* @return **mixed** First key of map, (generated) default value or an exception
Using this method doesn't affect the internal array pointer.
**Examples:**
```php
Map::from( ['a' => 1, 'b' => 2] )->firstKey();
// 'a'
Map::from( [] )->firstKey( 'x' );
// 'x'
Map::from( [] )->firstKey( new \Exception( 'error' ) );
// throws \Exception
Map::from( [] )->firstKey( function() { return rand(); } );
// random integer
```
**See also:**
* [first()](#first) - Returns the first element from the map
* [last()](#last) - Returns the last element from the map
* [lastKey()](#lastkey) - Returns the last key from the map
### flat()
Creates a new map with all sub-array elements added recursively.
```php
public function flat( int $depth = null ) : self
```
* @param **int|null** `$depth` Number of levels to flatten multi-dimensional arrays
* @return **self<int|string,mixed>** New map with all sub-array elements added into it recursively, up to the specified depth
The keys are not preserved and the new map elements will be numbered from
0-n. A value smaller than 1 for depth will return the same map elements
indexed from 0-n. Flattening does also work if elements implement the
"Traversable" interface (which the Map object does).
This method is similar than [collapse()](#collapse) but doesn't replace existing elements.
Keys are NOT preserved using this method!
**Examples:**
```php
Map::from( [[0, 1], [2, 3]] )->flat();
// [0, 1, 2, 3]
Map::from( [[0, 1], [[2, 3], 4]] )->flat();
// [0, 1, 2, 3, 4]
Map::from( [[0, 1], [[2, 3], 4]] )->flat( 1 );
// [0, 1, [2, 3], 4]
Map::from( [[0, 1], Map::from( [[2, 3], 4] )] )->flat();
// [0, 1, 2, 3, 4]
```
**See also:**
* [collapse()](#collapse) - Collapses all sub-array elements recursively to a new map
### flip()
Exchanges the keys with their values and vice versa.
```php
public function flip() : self
```
* @return **self<int|string,mixed>** New map with keys as values and values as keys
**Examples:**
```php
Map::from( ['a' => 'X', 'b' => 'Y'] )->flip();
// ['X' => 'a', 'Y' => 'b']
```
### float()
Returns an element by key and casts it to float if possible.
```php
public function float( $key, $default = 0.0 ) : float
```
* @param **int|string** `$key` Key or path to the requested item
* @param **mixed** `$default` Default value if key isn't found (will be casted to float)
* @return **float** Value from map or default value
This does also work to map values from multi-dimensional arrays by passing the keys
of the arrays separated by the delimiter ("/" by default), e.g. `key1/key2/key3`
to get `val` from `['key1' => ['key2' => ['key3' => 'val']]]`. The same applies to
public properties of objects or objects implementing `__isset()` and `__get()` methods.
**Examples:**
```php
Map::from( ['a' => true] )->float( 'a' );
// 1.0 (casted to float)
Map::from( ['a' => 1] )->float( 'a' );
// 1.0 (casted to float)
Map::from( ['a' => '1.1'] )->float( 'a' );
// 1.1 (casted to float)
Map::from( ['a' => '10'] )->float( 'a' );
// 10.0 (casted to float)
Map::from( ['a' => ['b' => ['c' => 1.1]]] )->float( 'a/b/c' );
// 1.1
Map::from( [] )->float( 'c', function() { return 1.1; } );
// 1.1
Map::from( [] )->float( 'a', 1 );
// 1.0 (default value used)
Map::from( [] )->float( 'a' );
// 0.0
Map::from( ['b' => ''] )->float( 'b' );
// 0.0 (casted to float)
Map::from( ['a' => 'abc'] )->float( 'a' );
// 0.0 (casted to float)
Map::from( ['b' => null] )->float( 'b' );
// 0.0 (null is not scalar)
Map::from( ['b' => [true]] )->float( 'b' );
// 0.0 (arrays are not scalar)
Map::from( ['b' => '#resource'] )->float( 'b' );
// 0.0 (resources are not scalar)
Map::from( ['b' => new \stdClass] )->float( 'b' );
// 0.0 (objects are not scalar)
Map::from( [] )->float( 'c', new \Exception( 'error' ) );
// throws exception
```
**See also:**
* [bool()](#bool) - Returns an element by key and casts it to boolean if possible
* [cast()](#cast) - Casts all entries to the passed type
* [get()](#get) - Returns an element from the map by key
* [int()](#int) - Returns an element by key and casts it to integer if possible
* [string()](#string) - Returns an element by key and casts it to string if possible
### from()
Creates a new map instance if the value isn't one already.
```php
public static function from( $elements = [] ) : self
```
* @param **mixed** `$elements` List of elements or single value
* @return **self<int|string,mixed>** New map
**Examples:**
```php
// array
Map::from( [] );
// null
Map::from( null );
// scalar
Map::from( 'a' );
// object
Map::from( new \stdClass() );
// map object
Map::from( new Map() );
// iterable object
Map::from( new ArrayObject() );
// closure evaluated lazily
Map::from( function() {
return [];
} );
```
**See also:**
* [fromJson()](#fromjson) - Creates a new map instance from a JSON string
### fromJson()
Creates a new map instance from a JSON string.
```php
public static function fromJson( string $json, int $options = JSON_BIGINT_AS_STRING ) : self
```
* @param **int** `$options` Combination of JSON_* constants
* @return **self<int|string,mixed>** New map from decoded JSON string
* @throws **\RuntimeException** If the passed JSON string is invalid
There are several options available for decoding the JSON string which are described in
the [PHP json_decode() manual](https://www.php.net/manual/en/function.json-decode.php).
The parameter can be a single JSON_* constant or a bitmask of several constants combine
by bitwise OR (|), e.g.:
This method creates a lazy Map and the string is decoded after calling
another method that operates on the Map contents. Thus, the exception in
case of an error isn't thrown immediately but after calling the next method.
```php
JSON_BIGINT_AS_STRING|JSON_INVALID_UTF8_IGNORE
```
**Examples:**
```php
Map::fromJson( '["a", "b"]' );
// ['a', 'b']
Map::fromJson( '{"a": "b"}' );
// ['a' => 'b']
Map::fromJson( '""' );
['']
```
**See also:**
* [from()](#from) - Creates a new map instance if the value isn't one already
### get()
Returns an element from the map by key.
```php
public function get( $key, $default = null )
```
* @param **int|string** `$key` Key or path to the requested item
* @param **mixed** `$default` Default value if no element matches
* @return **mixed** Value from map or default value
This does also work to map values from multi-dimensional arrays by passing the keys
of the arrays separated by the delimiter ("/" by default), e.g. `key1/key2/key3`
to get `val` from `['key1' => ['key2' => ['key3' => 'val']]]`. The same applies to
public properties of objects or objects implementing `__isset()` and `__get()` methods.
**Examples:**
```php
Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'a' );
// 'X'
Map::from( ['a' => 'X', 'b' => 'Y'] )->get( 'c', 'Z' );
// 'Z'
Map::from( ['a' => ['b' => ['c' => 'Y']]] )->get( 'a/b/c' );
// 'Y'
Map::from( [] )->get( 'c', new \Exception( 'error' ) );
// throws \Exception
Map::from( [] )->get( 'c', function() { return rand(); } );
// random integer
```
**See also:**
* [bool()](#bool) - Returns an element by key and casts it to boolean if possible
* [int()](#int) - Returns an element by key and casts it to integer if possible
* [float()](#float) - Returns an element by key and casts it to float if possible
* [pull()](#pull) - Returns and removes an element from the map by its key
* [set()](#set) - Sets an element in the map by key without returning a new map
* [string()](#string) - Returns an element by key and casts it to string if possible
### getIterator()
Returns an iterator for the elements.
```php
public function getIterator() : \ArrayIterator
```
* @return **\Iterator** Over map elements
This method will be used by e.g. `foreach()` to loop over all entries.
**Examples:**
```php
foreach( Map::from( ['a', 'b'] ) as $value ) {
// ...
}
```
### grep()
Returns only items which matches the regular expression.
```php
public function grep( string $pattern, int $flags = 0 ) : self
```
* @param **string** `$pattern` Regular expression pattern, e.g. "/ab/"
* @param **int** `$flags` PREG_GREP_INVERT to return elements not matching the pattern
* @return **self<int|string,mixed>** New map containing only the matched elements
All items are converted to string first before they are compared to the
regular expression. Thus, fractions of ".0" will be removed in float numbers
which may result in unexpected results. The keys are preserved using this method.
**Examples:**
```php
Map::from( ['ab', 'bc', 'cd'] )->grep( '/b/' );
// ['ab', 'bc']
Map::from( ['ab', 'bc', 'cd'] )->grep( '/a/', PREG_GREP_INVERT );
// ['bc', 'cd']
Map::from( [1.5, 0, 1.0, 'a'] )->grep( '/^(\d+)?\.\d+$/' );
// [1.5]
// float 1.0 is converted to string "1"
```
**See also:**
* [filter()](#filter) - Runs a filter over each element of the map and returns a new map
* [where()](#where) - Filters the list of elements by a given condition
### groupBy()
Groups associative array elements or objects by the passed key or closure.
```php
public function groupBy( $key ) : self
```
* @param **\Closure|string|int** `$key` Closure function with (item, idx) parameters returning the key or the key itself to group by
* @return **self<int|string,mixed>** New map with elements grouped by the given key
Instead of overwriting items with the same keys like to the [col()](#col) method does,
[groupBy()](#groupby) keeps all entries in sub-arrays. It's preserves the keys of the
orignal map entries too.
This does also work for multi-dimensional arrays by passing the keys
of the arrays separated by the delimiter ("/" by default), e.g. "key1/key2/key3"
to get "val" from ['key1' => ['key2' => ['key3' => 'val']]]. The same applies to
public properties of objects or objects implementing __isset() and __get() methods.
**Examples:**
```php
$list = [
10 => ['aid' => 123, 'code' => 'x-abc'],
20 => ['aid' => 123, 'code' => 'x-def'],
30 => ['aid' => 456, 'code' => 'x-def']
];
Map::from( $list )->groupBy( 'aid' );
/*
[
123 => [
10 => ['aid' => 123, 'code' => 'x-abc'],
20 => ['aid' => 123, 'code' => 'x-def']
],
456 => [
30 => ['aid' => 456, 'code' => 'x-def']
]
]
*/
Map::from( $list )->groupBy( function( $item, $key ) {
return substr( $item['code'], -3 );
} );
/*
[
'abc' => [
10 => ['aid' => 123, 'code' => 'x-abc']
],
'def' => [
20 => ['aid' => 123, 'code' => 'x-def'],
30 => ['aid' => 456, 'code' => 'x-def']
]
]
*/
```
In case the passed key doesn't exist in one or more items, these items are stored
in a sub-array using an empty string as key:
```php
$list = [
10 => ['aid' => 123, 'code' => 'x-abc'],
20 => ['aid' => 123, 'code' => 'x-def'],
30 => ['aid' => 456, 'code' => 'x-def']
];
Map::from( $list )->groupBy( 'xid' );
/*
[
'' => [
10 => ['aid' => 123, 'code' => 'x-abc'],
20 => ['aid' => 123, 'code' => 'x-def'],
30 => ['aid' => 456, 'code' => 'x-def']
]
]
*/
```
**See also:**
* [countBy()](#countby) - Counts how often the same values are in the map
### has()
Determines if a key or several keys exists in the map.
```php
public function has( $key ) : bool
```
* @param **array<int|string<|int|string** `$key` Key or path to the requested item
* @return **bool** TRUE if key is available in map, FALSE if not
If several keys are passed as array, all keys must exist in the map to
return TRUE.
This does also work to map values from multi-dimensional arrays by passing the keys
of the arrays separated by the delimiter ("/" by default), e.g. `key1/key2/key3`
to get `val` from `['key1' => ['key2' => ['key3' => 'val']]]`. The same applies to
public properties of objects or objects implementing `__isset()` and `__get()` methods.
**Examples:**
```php
Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'a' );
// true
Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'b'] );
// false
Map::from( ['a' => ['b' => ['c' => 'Y']]] )->has( 'a/b/c' );
// true
Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'c' );
// false
Map::from( ['a' => 'X', 'b' => 'Y'] )->has( ['a', 'c'] );
// false
Map::from( ['a' => 'X', 'b' => 'Y'] )->has( 'X' );
// false
```
### if()
Executes callbacks depending on the condition.
```php
public function if( $condition, \Closure $then, \Closure $else = null ) : self
```
* @param **\Closure|bool** `$condition` Boolean or function with (map) parameter returning a boolean
* @param **\Closure** `$then` Function with (map) parameter
* @param **\Closure|null** `$else` Function with (map) parameter (optional)
* @return **self<int|string,mixed>** New map for fluid interface
If callbacks for "then" and/or "else" are passed, these callbacks will be
executed and their returned value is passed back within a Map object. In
case no "then" or "else" closure is given, the method will return the same
map object if the condition is true or an empty map object if it's false.
**Examples:**
```php
Map::from( ['a' => 1, 'b' => 0] )->if(
'a' == 'b',
function( Map $_ ) { echo "then"; }
);
// no output
Map::from( ['a' => 1, 'b' => 0] )->if(
function( Map $map ) { return $map->has( 'a' ); },
function( Map $_ ) { echo "then"; },
function( Map $_ ) { echo "else"; }
);
// then
Map::from( ['a' => 1, 'b' => 0] )->if(
fn( Map $map ) => $map->has( 'c' ),
function( Map $_ ) { echo "then"; },
function( Map $_ ) { echo "else"; }
);
// else
Map::from( ['a', 'b'] )->if( true, function( $map ) {
return $map->push( 'c' );
} );
// ['a', 'b', 'c']
Map::from( ['a', 'b'] )->if( false, null, function( $map ) {
return $map->pop();
} );
// ['b']
```
Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
(a short form for anonymous closures) as parameters. The automatically have access
to previously defined variables but can not modify them. Also, they can not have
a void return type and must/will always return something. Details about
[PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
**See also:**
* [ifAny()](#ifany) - Executes callbacks depending if the map contains elements or not
* [ifEmpty()](#ifempty) - Executes callbacks depending if the map is empty or not
### ifAny()
* Executes callbacks depending if the map contains elements or not.
```php
public function ifAny( \Closure $then = null, \Closure $else = null ) : self
```
* @param **\Closure|null** `$then` Function with (map, condition) parameter (optional)
* @param **\Closure|null** `$else` Function with (map, condition) parameter (optional)
* @return **self** New map for fluid interface
If callbacks for "then" and/or "else" are passed, these callbacks will be
executed and their returned value is passed back within a Map object. In
case no "then" or "else" closure is given, the method will return the same
map object.
**Examples:**
```php
Map::from( ['a'] )->ifAny( function( $map ) {
$map->push( 'b' );
} );
// ['a', 'b']
Map::from( [] )->ifAny( null, function( $map ) {
return $map->push( 'b' );
} );
// ['b']
Map::from( ['a'] )->ifAny( function( $map ) {
return 'c';
} );
// ['c']
```
Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
(a short form for anonymous closures) as parameters. The automatically have access
to previously defined variables but can not modify them. Also, they can not have
a void return type and must/will always return something. Details about
[PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
**See also:**
* [if()](#if) - Executes callbacks depending on the condition
* [ifEmpty()](#ifempty) - Executes callbacks depending if the map is empty or not
### ifEmpty()
* Executes callbacks depending if the map is empty or not.
```php
public function ifEmpty( \Closure $then = null, \Closure $else = null ) : self
```
* @param **\Closure|null** `$then` Function with (map, condition) parameter (optional)
* @param **\Closure|null** `$else` Function with (map, condition) parameter (optional)
* @return **self** New map for fluid interface
If callbacks for "then" and/or "else" are passed, these callbacks will be
executed and their returned value is passed back within a Map object. In
case no "then" or "else" closure is given, the method will return the same
map object.
**Examples:**
```php
Map::from( [] )->ifEmpty( function( $map ) {
$map->push( 'a' );
} );
// ['a']
Map::from( ['a'] )->ifEmpty( null, function( $map ) {
return $map->push( 'b' );
} );
// ['a', 'b']
```
Since PHP 7.4, you can also pass arrow function like `fn($map) => $map->has('c')`
(a short form for anonymous closures) as parameters. The automatically have access
to previously defined variables but can not modify them. Also, they can not have
a void return type and must/will always return something. Details about
[PHP arrow functions](https://www.php.net/manual/en/functions.arrow.php)
**See also:**
* [if()](#if) - Executes callbacks depending on the condition
* [ifAny()](#ifany) - Executes callbacks depending if the map contains elements or not
### implements()
Tests if all entries in the map are objects implementing the given interface.
```php
public function implements( string $interface, $throw = false ) : bool
```
* @param **string** `$interface` Name of the interface that must be implemented
* @param **\Throwable|bool** `$throw` Passing TRUE or an exception name will throw the exception instead of returning FALSE
* @return **bool** TRUE if all entries implement the interface or FALSE if at least one doesn't
* @throws **\UnexpectedValueException|\Throwable** If one entry doesn't implement the interface
**Examples:**
```php
Map::from( [new Map(), new Map()] )->implements( '\Countable' );
// true
Map::from( [new Map(), new \stdClass()] )->implements( '\Countable' );
// false
Map::from( [new Map(), 123] )->implements( '\Countable' );
// false
Map::from( [new Map(), 123] )->implements( '\Countable', true );
// throws \UnexpectedValueException
Map::from( [new Map(), 123] )->implements( '\Countable', '\RuntimeException' );
// throws \RuntimeException
```
### in()
Tests if the passed element or elements are part of the map.
```php
public function in( $element, bool $strict = false ) : bool
```
* @param **mixed|array** `$element` Element or elements to search for in the map
* @param **bool** `$strict` TRUE to check the type too, using FALSE '1' and 1 will be the same
* @return **bool** TRUE if all elements are available in map, FALSE if not
**Examples:**
```php
Map::from( ['a', 'b'] )->in( 'a' );
// true
Map::from( ['a', 'b'] )->in( ['a', 'b'] );
// true
Map::from( ['a', 'b'] )->in( 'x' );
// false
Map::from( ['a', 'b'] )->in( ['a', 'x'] );
// false
Map::from( ['1', '2'] )->in( 2, true );
// false
```
**See also:**
* [compare()](#compare) - Compares the value against all map elements
* [contains()](#contains) - Tests if an item exists in the map
* [includes()](#includes) - Tests if element is included
* [none()](#none) - Tests if none of the elements are part of the map
### includes()
Tests if the passed element or elements are part of the map (alias).
```php
public function includes( $element, bool $strict = false ) : bool
```
* @param **mixed|array** `$element` Element or elements to search for in the map
* @param **bool** `$strict` TRUE to check the type too, using FALSE '1' and 1 will be the same
* @return **bool** TRUE if all elements are available in map, FALSE if not
This method is an alias for [in()](#in). For performance reasons, `in()` should be preferred
because it uses one method call less than `includes()`.
**See also:**
* [compare()](#compare) - Compares the value against all map elements
* [contains()](#contains) - Tests if an item exists in the map
* [in()](#in) - Tests if element is included
* [none()](#none) - Tests if none of the elements are part of the map
### index()
Returns the numerical index of the given key.
```php
public function index( $value ) : ?int
```
* @param **\Closure|string|int** `$value` Key to search for or function with (key) parameters return TRUE if key is found
* @return **int|null** Position of the found value (zero based) or NULL if not found
**Examples:**
```php
Map::from( [4 => 'a', 8 => 'b'] )->index( '8' );
// 1
Map::from( [4 => 'a', 8 => 'b'] )->index( function( $key ) {
return $key == '8';
} );
// 1
```
Both examples will return "1" because the value "b" is at the second position
and the returned index is zero based so the first item has the index "0".
**See also:**
* [at()](#at) - Returns the value at the given position
* [pos()](#pos) - Returns the numerical index of the value
### insertAfter()
Inserts the value or values after the given element.
```php
public function insertAfter( $element, $value ) : self
```
* @param **mixed** `$element` Element after the value is inserted
* @param **mixed** `$value` Element or list of elements to insert
* @return **self<int|string,mixed>** Updated map for fluid interface
Numerical array indexes are not preserved.
**Examples:**
```php
Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAfter( 'foo', 'baz' );
// ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
Map::from( ['foo', 'bar'] )->insertAfter( 'foo', ['baz', 'boo'] );
// ['foo', 'baz', 'boo', 'bar']
Map::from( ['foo', 'bar'] )->insertAfter( null, 'baz' );
// ['foo', 'bar', 'baz']
```
**See also:**
* [insertAt()](#insertat) - Inserts the item at the given position in the map
* [insertBefore()](#insertbefore) - Inserts the value or values before the given element
### insertAt()
Inserts the item at the given position in the map.
```php
public function insertAt( int $pos, $element, $key = null ) : self
```
* @param **int** `$pos` Position the element it should be inserted at
* @param **mixed** `$element` Element to be inserted
* @param **mixed|null** `$key` Element key or NULL to assign an integer key automatically
* @return **self<int|string,mixed>** Updated map for fluid interface
**Examples:**
```php
Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 0, 'baz' );
// [0 => 'baz', 'a' => 'foo', 'b' => 'bar']
Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 1, 'baz', 'c' );
// ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( 5, 'baz' );
// ['a' => 'foo', 'b' => 'bar', 'c' => 'baz']
Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertAt( -1, 'baz', 'c' );
// ['a' => 'foo', 'c' => 'baz', 'b' => 'bar']
```
**See also:**
* [insertAfter()](#insertafter) - Inserts the value or values after the given element
* [insertBefore()](#insertbefore) - Inserts the value or values before the given element
### insertBefore()
Inserts the value or values before the given element.
```php
public function insertBefore( $element, $value ) : self
```
* @param **mixed** `$element` Element before the value is inserted
* @param **mixed** `$value` Element or list of elements to insert
* @return **self<int|string,mixed>** Updated map for fluid interface
Numerical array indexes are not preserved.
**Examples:**
```php
Map::from( ['a' => 'foo', 'b' => 'bar'] )->insertBefore( 'bar', 'baz' );
// ['a' => 'foo', 0 => 'baz', 'b' => 'bar']
Map::from( ['foo', 'bar'] )->insertBefore( 'bar', ['baz', 'boo'] );
// ['foo', 'baz', 'boo', 'bar']
Map::from( ['foo', 'bar'] )->insertBefore( null, 'baz' );
// ['foo', 'bar', 'baz']
```
**See also:**
* [insertAfter()](#insertafter) - Inserts the value or values after the given element
* [insertAt()](#insertat) - Inserts the item at the given position in the map
### inString()
Tests if the passed value or value are part of the strings in the map.
This method is deprecated in favor of the multi-byte aware [strContains()](#strcontains) method.
```php
public function inString( $value, bool $case = true ) : bool
```
* @param **array|string** `$value` Value or values to compare the map elements, will be casted to string type
* @param **bool** `$case` TRUE if comparison is case sensitive, FALSE to ignore upper/lower case
* @return **bool** TRUE If at least one element matches, FALSE if value is not in any string of the map
All scalar values (bool, float, int and string) are casted to string values before
comparing to the given value. Non-scalar values in the map are ignored.
**Examples:**
```php
Map::from( ['abc'] )->inString( 'c' );
// true ('abc' contains 'c')
Map::from( ['abc'] )->inString( 'bc' );
// true ('abc' contains 'bc')
Map::from( [12345] )->inString( '23' );
// true ('12345' contains '23')
Map::from( [123.4] )->inString( 23.4 );
// true ('123.4' contains '23.4')
Map::from( [12345] )->inString( false );
// true ('12345' contains '')
Map::from( [12345] )->inString( true );
// true ('12345' contains '1')
Map::from( [false] )->inString( false );
// true ('' contains '')
Map::from( ['abc'] )->inString( '' );
// true ('abc' contains '')
Map::from( [''] )->inString( false );
// true ('' contains '')
Map::from( ['abc'] )->inString( 'BC', false );
// true ('abc' contains 'BC' when case-insentive)
Map::from( ['abc', 'def'] )->inString( ['de', 'xy'] );
// true ('def' contains 'de')
Map::from( ['abc', 'def'] )->inString( ['E', 'x'] );
// false (doesn't contain "E" when case sensitive)
Map::from( ['abc', 'def'] )->inString( 'E' );
// false (doesn't contain "E" when case sensitive)
Map::from( [23456] )->inString( true );
// false ('23456' doesn't contain '1')
Map::from( [false] )->inString( 0 );
// false ('' doesn't contain '0')
```
**See also:**
* [strContains()](#strcontains) - Tests if at least one of the passed strings is part of at least one entry
* [strContainsAll()](#strcontainsall) - Tests if all of the entries contains one of the passed strings
### int()
Returns an element by key and casts it to integer if possible.
```php
public function int( $key, $default = 0 ) : int
```
* @param **int|string** `$key` Key or path to the requested item
* @param **mixed** `$default` Default value if key isn't found (will be casted to int)
* @return **int** Value from map or default value
This does also work to map values from multi-dimensional arrays by passing the keys
of the arrays separated by the delimiter ("/" by default), e.g. `key1/key2/key3`
to get `val` from `['key1' => ['key2' => ['key3' => 'val']]]`. The same applies to
public properties of objects or objects implementing `__isset()` and `__get()` methods.
**Examples:**
```php
Map::from( ['a' => true] )->int( 'a' );
// 1
Map::from( ['a' => '1'] )->int( 'a' );
// 1 (casted to integer)
Map::from( ['a' => 1.1] )->int( 'a' );
// 1 (casted to integer)
Map::from( ['a' => '10'] )->int( 'a' );
// 10 (casted to integer)
Map::from( ['a' => ['b' => ['c' => 1]]] )->int( 'a/b/c' );
// 1
Map::from( [] )->int( 'c', function() { return rand( 1, 1 ); } );
// 1
Map::from( [] )->int( 'a', 1 );
// 1 (default value used)
Map::from( [] )->int( 'a' );
// 0
Map::from( ['b' => ''] )->int( 'b' );
// 0 (casted to integer)
Map::from( ['a' => 'abc'] )->int( 'a' );
// 0 (casted to integer)
Map::from( ['b' => null] )->int( 'b' );
// 0 (null is not scalar)
Map::from( ['b' => [true]] )->int( 'b' );
// 0 (arrays are not scalar)
Map::from( ['b' => '#resource'] )->int( 'b' );
// 0 (resources are not scalar)
Map::from( ['b' => new \stdClass] )->int( 'b' );
// 0 (objects are not scalar)
Map::from( [] )->int( 'c', new \Exception( 'error' ) );
// throws exception
```
**See also:**
* [bool()](#bool) - Returns an element by key and casts it to boolean if possible
* [cast()](#cast) - Casts all entries to the passed type
* [get()](#get) - Returns an element from the map by key
* [float()](#float) - Returns an element by key and casts it to float if possible
* [string()](#string) - Returns an element by key and casts it to string if possible
### intersect()
Returns all values in a new map that are available in both, the map and the given elements.
```php
public function intersect( iterable $elements, callable $callback = null ) : self
```
* @param **iterable<int|string,mixed>** `$elements` List of elements
* @param **callable|null** `$callback` Function with (valueA, valueB) parameters and returns -1 (<), 0 (=) and 1 (>)
* @return **self<int|string,mixed>** New map
The keys are preserved using this method.
**Examples:**
```php
Map::from( ['a' => 'foo', 'b' => 'bar'] )->intersect( ['bar'] );
// ['b' => 'bar']
```
If a callback is passed, the given function will be used to compare the values.
The function must accept two parameters (vaA, valB) and must return
-1 if value A is smaller than value B, 0 if both are equal and 1 if value A is
greater than value B. Both, a method name and an anonymous function can be passed:
```php
Map::from( [0 => 'a'] )->intersect( [0 => 'A'], 'strcasecmp' );
// ['a']
Map::from( ['b' => 'a'] )->intersect( ['B' => 'A'], 'strcasecmp' );
// ['a']
Map::from( ['b' => 'a'] )->intersect( ['c' => 'A'], function( $valA, $valB ) {
return strtolower( $valA ) <=> strtolower( $valB );
} );
// ['a']
```
**See also:**
* [intersectAssoc()](#intersectassoc) - Returns all values in a new map that are available in both, the map and the given elements while comparing the keys too
* [intersectKeys()](#intersectkeys) - Returns all values in a new map that are available in both, the map and t