Download the PHP package aimeos/map without Composer

On this page you can find all versions of the php package aimeos/map. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package map

Build Status Coverage Status License Latest Stable Version Stars Downloads

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.

Supported PHP versions:

Table of contents

Why PHP Map

Instead of:

Only use:

You can still use:

Use callbacks:

Also, the map object allows you to pass anonymous functions to a lot of methods, e.g.:

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:

This will call setStatus( 1 ) on both objects. If setStatus() implementation returns $this, the new map will also contain:

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:

Methods

Create

Access

Add

Aggregate

Debug

OrderBy

Shorten

Test

Transform

Misc

Method documentation

is_map() function

Tests if the variable is a map object

Examples:

map() function

Returns a new map for the passed elements.

Examples:

__construct()

Creates a new map object.

Examples:

__call()

Handles dynamic calls to custom methods for the class.

Calls a custom method added by Map::method(). The called method has access to the internal array by using $this->items.

Examples:

This does also allow calling object methods if the items are objects:

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.

__callStatic()

Handles static calls to custom methods for the class.

Calls a custom method added by Map::method() statically. The called method has no access to the internal array because no object is available.

Examples:

after()

Returns the elements after the given one.

The keys are preserved using this method.

Examples:

all()

Returns the elements as a plain array.

Examples:

arsort()

Sorts all elements in reverse order and maintains the key association.

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:

Examples:

asort()

Sorts all elements and maintains the key association.

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:

Examples:

at()

Returns the value at the given position.

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:

avg()

Returns the average of all integer and float values in the map.

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:

before()

Returns the elements before the given one.

The keys are preserved using this method.

Examples:

bool()

Returns an element by key and casts it to boolean if possible.

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:

call()

Calls the given method on all items and returns the result.

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:

cast()

Casts all entries to the passed type.

Casting arrays and objects to scalar values won't return anything useful!

Examples:

chunk()

Chunks the map into arrays with the given number of elements.

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() when you iterate over the map.

Examples:

clear()

Removes all elements from the current map.

Examples:

clone()

Clones the map and all objects within.

The objects within the Map are NOT the same as before but new cloned objects. This is different to copy(), which doesn't clone the objects within.

The keys are preserved using this method.

Examples:

col()

Returns the values of a single column/property from an array of arrays or list of elements in a new map.

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:

collapse()

Collapses all sub-array elements recursively to a new map.

The keys are preserved and already existing elements will be overwritten. This is also true for numeric keys! This method is similar than 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:

combine()

Combines the values of the map as keys with the passed elements as values.

Examples:

compare()

Compares the value against all map elements.

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:

concat()

Pushs all of the given elements onto the map without creating a new map.

The keys of the passed elements are NOT preserved!

Examples:

contains()

Determines if an item exists in the map.

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.

Check the where()] method for available operators.

Examples:

copy()

Creates a new map with the same elements.

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:

count()

Counts the number of elements in the map.

Examples:

countBy()

Counts how often the same values are in the map.

Examples:

dd()

Dumps the map content and terminates the script.

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:

The first() method isn't executed at all.

delimiter()

Sets or returns the seperator for paths to values in multi-dimensional arrays or objects.

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() method instead.

Examples:

diff()

Returns the keys/values in the map whose values are not present in the passed elements in a new map.

Examples:

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:

All examples will return an empty map because both contain the same values when compared case insensitive.

The keys are preserved using this method.

diffAssoc()

Returns the keys/values in the map whose keys AND values are not present in the passed elements in a new map.

Examples:

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:

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.

diffKeys()

Returns the key/value pairs from the map whose keys are not present in the passed elements in a new map.

Examples:

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:

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.

dump()

Dumps the map content using the given function (print_r by default).

The dump() method is very helpful to see what are the map elements passed between two map methods in a method call chain.

Examples:

duplicates()

Returns the duplicate values from the 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:

each()

Executes a callback over each entry until FALSE is returned.

Examples:

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.

The method is equivalent to isEmpty().

Examples:

equals()

Tests if the passed elements are equal to the elements in the map.

The method differs to 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:

Examples:

every()

Verifies that all elements pass the test of the given callback.

Examples:

except()

Returns a new map without the passed element keys.

The keys in the result map are preserved.

Examples:

explode()

Creates a new map with the string splitted by the delimiter.

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:

filter()

Runs a filter over each element of the map and returns a 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:

The keys in the result map are preserved.

Examples:

find()

Returns the first matching element where the callback returns TRUE.

Examples:

first()

Returns the first element from the map.

Examples:

firstKey()

Returns the first key from the map.

Examples:

flat()

Creates a new map with all sub-array elements added recursively.

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() but doesn't replace existing elements. Keys are NOT preserved using this method!

Examples:

flip()

Exchanges the keys with their values and vice versa.

Examples:

float()

Returns an element by key and casts it to float if possible.

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:

from()

Creates a new map instance if the value isn't one already.

Examples:

fromJson()

Creates a new map instance from a JSON string.

There are several options available for decoding the JSON string which are described in the PHP json_decode() manual. 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.

Examples:

get()

Returns an element from the map by key.

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:

getIterator()

Returns an iterator for the elements.

This method will be used by e.g. foreach() to loop over all entries.

Examples:

grep()

Returns only items which matches the regular expression.

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:

groupBy()

Groups associative array elements or objects by the passed key or closure.

Instead of overwriting items with the same keys like to the col() method does, groupBy() keeps all entries in sub-arrays. It's preserves the keys of the orignal map entries too.

Examples:

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:

has()

Determines if a key or several keys exists in the map.

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:

if()

Executes callbacks depending on the condition.

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:

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

ifAny()

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:

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

ifEmpty()

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:

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

implements()

Tests if all entries in the map are objects implementing the given interface.

Examples:

in()

Tests if the passed element or elements are part of the map.

Examples:

includes()

Tests if the passed element or elements are part of the map.

This method is an alias for in(). For performance reasons, in() should be preferred because it uses one method call less than includes().

Examples:

index()

Returns the numerical index of the given key.

Examples:

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".

insertAfter()

Inserts the value or values after the given element.

Numerical array indexes are not preserved.

Examples:

insertAt()

Inserts the item at the given position in the map.

Examples:

insertBefore()

Inserts the value or values before the given element.

Numerical array indexes are not preserved.

Examples:

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() method.

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:

int()

Returns an element by key and casts it to integer if possible.

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:

intersect()

Returns all values in a new map that are available in both, the map and the given elements.

The keys are preserved using this method.

Examples:

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:

intersectAssoc()

Returns all values in a new map that are available in both, the map and the given elements while comparing the keys too.

The keys are preserved using this method.

Examples:

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:

intersectKeys()

Returns all values in a new map that are available in both, the map and the given elements by comparing the keys only.

The keys are preserved using this method.

Examples:

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:

is()

Tests if the map consists of the same keys and values

Examples:

isEmpty()

Determines if the map is empty or not.

The method is equivalent to empty().

Examples:

isObject()

Determines if all entries are objects.

Examples:

isNumeric()

Determines if all entries are numeric values.

Examples:

isScalar()

Determines if all entries are scalar values.

Examples:

join()

Concatenates the string representation of all elements.

Objects that implement __toString() does also work, otherwise (and in case of arrays) a PHP notice is generated. NULL and FALSE values are treated as empty strings.

Examples:

jsonSerialize()

Specifies the data which should be serialized to JSON by json_encode().

Examples:

keys()

Returns the keys of the map elements in a new map object.

Examples:

krsort()

Sorts the elements by their keys in reverse order.

The parameter modifies how the keys are compared. Possible values are:

The keys are preserved using this method and no new map is created.

Examples:

ksort()

Sorts the elements by their keys.

The parameter modifies how the keys are compared. Possible values are:

The keys are preserved using this method and no new map is created.

Examples:

last()

Returns the last element from the map.

Examples:

lastKey()

Returns the last key from the map.

Examples:

ltrim()

Removes the passed characters from the left of all strings.

Examples:

map()

Calls the passed function once for each element and returns a new map for the result.

The keys are preserved using this method.

Examples:

max()

Returns the maximum value of all elements.

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.

Be careful comparing elements of different types because this can have unpredictable results due to the PHP comparison rules

Examples:

merge()

Merges the map with the given elements without returning a new map.

Elements with the same non-numeric keys will be overwritten, elements with the same numeric keys will be added.

The method is similar to concat() instead.

The keys are preserved using this method.

Examples:

method()

Registers a custom method or returns the existing one.

The registed method has access to the class properties if called non-static.

Examples:

Static calls can't access $this->elements but can operate on the parameter values:

min()

Returns the minimum value of all elements.

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.

Be careful comparing elements of different types because this can have unpredictable results due to the PHP comparison rules

Examples:

none()

Tests if none of the elements are part of the map.

Examples:

nth()

Returns every nth element from the map.

Examples:

offsetExists()

Determines if an element exists at an offset.

Examples:

offsetGet()

Returns an element at a given offset.

public function offsetGet( $key )

Examples:

$map = Map::from( ['a' => 1, 'b' => 3] );

$map['b'];
// 3

offsetSet()

Sets the element at a given offset.

public function offsetSet( $key, $value )

Examples:

$map = Map::from( ['a' => 1] );

$map['b'] = 2;
// ['a' => 1, 'b' => 2]

$map[0] = 4;
// ['a' => 1, 'b' => 2, 0 => 4]

offsetUnset()

Unsets the element at a given offset.

public function offsetUnset( $key )

Examples:

$map = Map::from( ['a' => 1] );

unset( $map['a'] );
// []

only()

Returns a new map with only those elements specified by the given keys.

public function only( $keys ) : self

The keys are preserved using this method.

Examples:

Map::from( ['a' => 1, 0 => 'b'] )->only( 'a' );
// ['a' => 1]

Map::from( ['a' => 1, 0 => 'b', 1 => 'c'] )->only( [0, 1] );
// [0 => 'b', 1 => 'c']

order()

Returns a new map with elements ordered by the passed keys.

public function order( iterable $keys ) : self

The keys are preserved using this method.

Examples:

Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 'a'] );
// [0 => 'b', 1 => 'c', 'a' => 1]

Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1, 2] );
// [0 => 'b', 1 => 'c', 2 => null]

Map::from( ['a' => 1, 1 => 'c', 0 => 'b'] )->order( [0, 1] );
// [0 => 'b', 1 => 'c']

pad()

Fill up to the specified length with the given value

public function pad( int $size, $value = null ) : self

In case the given number is smaller than the number of element that are already in the list, the map is unchanged. If the size is positive, the new elements are padded on the right, if it's negative then the elements are padded on the left.

Associative keys are preserved, numerical keys are replaced and numerical keys are used for the new elements.

Examples:

Map::from( [1, 2, 3] )->pad( 5 );
// [1, 2, 3, null, null]

Map::from( [1, 2, 3] )->pad( -5 );
// [null, null, 1, 2, 3]

Map::from( [1, 2, 3] )->pad( 5, '0' );
// [1, 2, 3, '0', '0']

Map::from( [1, 2, 3] )->pad( 2 );
// [1, 2, 3]

Map::from( [10 => 1, 20 => 2] )->pad( 3 );
// [0 => 1, 1 => 2, 2 => null]

Map::from( ['a' => 1, 'b' => 2] )->pad( 3, 3 );
// ['a' => 1, 'b' => 2, 0 => 3]

partition()

Breaks the list of elements into the given number of groups.

public function partition( $num ) : self

The keys of the original map are preserved in the returned map.

Examples:

Map::from( [1, 2, 3, 4, 5] )->partition( 3 );
// [[0 => 1, 1 => 2], [2 => 3, 3 => 4], [4 => 5]]

Map::from( [1, 2, 3, 4, 5] )->partition( function( $val, $idx ) {
    return $idx % 3;
} );
// [0 => [0 => 1, 3 => 4], 1 => [1 => 2, 4 => 5], 2 => [2 => 3]]

pipe()

Passes the map to the given callback and return the result.

public function pipe( \Closure $callback )

Examples:

Map::from( ['a', 'b'] )->pipe( function( $map ) {
    return strrev( $map->join( '-' ) );
} );
// 'b-a'

pluck()

Returns the values of a single column/property from an array of arrays or list of elements in a new map.

public function pluck( string $valuecol = null, string $indexcol = null ) : self

This method is an alias for col(). For performance reasons, col() should be preferred because it uses one method call less than pluck().

pop()

Returns and removes the last element from the map.

public function pop()

Examples:

Map::from( ['a', 'b'] )->pop();
// 'b', map contains ['a']

pos

Returns the numerical index of the value.

public function pos( $value ) : ?int

Examples:

Map::from( [4 => 'a', 8 => 'b'] )->pos( 'b' );
// 1

Map::from( [4 => 'a', 8 => 'b'] )->pos( function( $item, $key ) {
    return $item === 'b';
} );
// 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".

prefix

Adds a prefix in front of each map entry.

public function prefix( $prefix, int $depth = null ) : self

By default, nested arrays are walked recusively so all entries at all levels are prefixed. The keys of the original map are preserved in the returned map.

Examples:

Map::from( ['a', 'b'] )->prefix( '1-' );
// ['1-a', '1-b']

Map::from( ['a', ['b']] )->prefix( '1-' );
// ['1-a', ['1-b']]

Map::from( ['a', ['b']] )->prefix( '1-', 1 );
// ['1-a', ['b']]

Map::from( ['a', 'b'] )->prefix( function( $item, $key ) {
    return ( ord( $item ) + ord( $key ) ) . '-';
} );
// ['145-a', '147-b']

prepend()

Pushes an element onto the beginning of the map without returning a new map.

public function prepend( $value, $key = null ) : self

This method is an alias for the unshift() method.

Examples:

Map::from( ['a', 'b'] )->prepend( 'd' );
// ['d', 'a', 'b']

Map::from( ['a', 'b'] )->prepend( 'd', 'first' );
// ['first' => 'd', 0 => 'a', 1 => 'b']

pull()

Returns and removes an element from the map by its key.

public function pull( $key, $default = null )

Examples:

Map::from( ['a', 'b', 'c'] )->pull( 1 );
// 'b', map contains ['a', 'c']

Map::from( ['a', 'b', 'c'] )->pull( 'x', 'none' );
// 'none', map contains ['a', 'b', 'c']

push()

Adds an element onto the end of the map without returning a new map.

public function push( $value ) : self

Examples:

Map::from( ['a', 'b'] )->push( 'aa' );
// ['a', 'b', 'aa']

put()

Sets the given key and value in the map without returning a new map.

public function put( $key, $value ) : self

This method is an alias for set(). For performance reasons, set() should be preferred because it uses one method call less than put().

Examples:

Map::from( ['a'] )->put( 1, 'b' );
// [0 => 'a', 1 => 'b']

Map::from( ['a'] )->put( 0, 'b' );
// [0 => 'b']

random()

Returns one or more random element from the map.

public function random( int $max = 1 ) : self

The less elements are in the map, the less random the order will be, especially if the maximum number of values is high or close to the number of elements.

The keys of the original map are preserved in the returned map.

Examples:

Map::from( [2, 4, 8, 16] )->random();
// [2 => 8] or any other key/value pair

Map::from( [2, 4, 8, 16] )->random( 2 );
// [3 => 16, 0 => 2] or any other key/value pair

Map::from( [2, 4, 8, 16] )->random( 5 );
// [0 => 2,  1 => 4, 2 => 8, 3 => 16] in random order

reduce()

Iteratively reduces the array to a single value using a callback function.

public function reduce( callable $callback, $initial = null )

Afterwards, the map will be empty.

Examples:

Map::from( [2, 8] )->reduce( function( $result, $value ) {
    return $result += $value;
}, 10 );
// 20 because 10 + 2 + 8 and map equals []

reject()

Removes all matched elements and returns a new map.

public function reject( $callback = true ) : self

This method is the inverse of the filter() and should return TRUE if the item should be removed from the returned map.

If no callback is passed, all values which are NOT empty, null or false will be removed. The keys of the original map are preserved in the returned map.

Examples:

Map::from( [2 => 'a', 6 => 'b', 13 => 'm', 30 => 'z'] )->reject( function( $value, $key ) {
    return $value < 'm';
} );
// [13 => 'm', 30 => 'z']

Map::from( [2 => 'a', 13 => 'm', 30 => 'z'] )->reject( 'm' );
// [2 => 'a', 30 => 'z']

Map::from( [2 => 'a', 6 => null, 13 => 'm'] )->reject();
// [6 => null]

rekey()

Changes the keys according to the passed function.

public function rekey( callable $callback ) : self

Examples:

Map::from( ['a' => 2, 'b' => 4] )->rekey( function( $value, $key ) {
    return 'key-' . $key;
} );
// ['key-a' => 2, 'key-b' => 4]

remove()

Removes one or more elements from the map by its keys without returning a new map.

public function remove( $keys ) : self

Examples:

Map::from( ['a' => 1, 2 => 'b'] )->remove( 'a' );
// [2 => 'b']

Map::from( ['a' => 1, 2 => 'b'] )->remove( [2, 'a'] );
// []

replace()

Replaces elements in the map with the given elements without returning a new map.

public function replace( iterable $elements, bool $recursive = true ) : self

The method is similar to merge() but also replaces elements with numeric keys. These would be added by merge() with a new numeric key.

The keys are preserved in the returned map.

Examples:

Map::from( ['a' => 1, 2 => 'b'] )->replace( ['a' => 2] );
// ['a' => 2, 2 => 'b']

Map::from( ['a' => 1, 'b' => ['c' => 3, 'd' => 4]] )->replace( ['b' => ['c' => 9]] );
// ['a' => 1, 'b' => ['c' => 9, 'd' => 4]]

reverse()

Reverses the element order without returning a new map.

public function reverse() : self

The keys are preserved using this method.

Examples:

Map::from( ['a', 'b'] )->reverse();
// ['b', 'a']

Map::from( ['name' => 'test', 'last' => 'user'] )->reverse();
// ['last' => 'user', 'name' => 'test']

rsort()

Sorts all elements in reverse order without maintaining the key association.

public function rsort( int $options = SORT_REGULAR ) : self

The parameter modifies how the values are compared. Possible parameter values are:

The keys are NOT preserved and elements get a new index. No new map is created.

Examples:

Map::from( ['a' => 1, 'b' => 0] )->rsort();
// [0 => 1, 1 => 0]

Map::from( [0 => 'b', 1 => 'a'] )->rsort();
// [0 => 'b', 1 => 'a']

Map::from( [0 => 'C', 1 => 'b'] )->rsort();
// [0 => 'b', 1 => 'C']

Map::from( [0 => 'C', 1 => 'b'] )->rsort( SORT_STRING|SORT_FLAG_CASE );
// [0 => 'C', 1 => 'b'] because 'C' -> 'c' and 'c' > 'b'

rtrim()

Removes the passed characters from the right of all strings.

public function rtrim( string $chars = " \n\r\t\v\x00" ) : self

Examples:

Map::from( [" abc\n", "\tcde\r\n"] )->rtrim();
// [" abc", "\tcde"]

Map::from( ["a b c", "cbxa"] )->rtrim( 'abc' );
// ["a b ", "cbx"]

search()

Searches the map for a given value and return the corresponding key if successful.

public function search( $value, $strict = true )

Examples:

Map::from( ['a', 'b', 'c'] )->search( 'b' );
// 1

Map::from( [1, 2, 3] )->search( '2', true );
// null because the types doesn't match (int vs. string)

sep()

Sets the seperator for paths to values in multi-dimensional arrays or objects.

public static function sep( string $char ) : self

This method only changes the separator for the current map instance. To change the separator for all maps created afterwards, use the static Map::delimiter() method instead.

Examples:

Map::from( ['foo' => ['bar' => 'baz']] )->sep( '.' )->get( 'foo.bar' );
// 'baz'

set()

Sets an element in the map by key without returning a new map.

public function set( $key, $value ) : self

Examples:

Map::from( ['a'] )->set( 1, 'b' );
// [0 => 'a', 1 => 'b']

Map::from( ['a'] )->set( 0, 'b' );
// [0 => 'b']

shift()

Returns and removes the first element from the map.

public function shift()

Examples:

Map::from( ['a', 'b'] )->shift();
// 'a'

Map::from( [] )->shift();
// null

Performance note:

The bigger the list, the higher the performance impact because shift() reindexes all existing elements. Usually, it's better to reverse() the list and pop() entries from the list afterwards if a significant number of elements should be removed from the list:

$map->reverse()->pop();

instead of

$map->shift();

shuffle()

Shuffles the elements in the map without returning a new map.

public function shuffle( bool $assoc = false ) : self

Examples:

Map::from( [2 => 'a', 4 => 'b'] )->shuffle();
// ['a', 'b'] in random order with new keys

Map::from( [2 => 'a', 4 => 'b'] )->shuffle( true );
// [2 => 'a', 4 => 'b'] in random order with keys preserved

skip()

Returns a new map with the given number of items skipped.

public function skip( $offset ) : self

The keys of the items returned in the new map are the same as in the original one.

Examples:

Map::from( [1, 2, 3, 4] )->skip( 2 );
// [2 => 3, 3 => 4]

Map::from( [1, 2, 3, 4] )->skip( function( $item, $key ) {
    return $item < 4;
} );
// [3 => 4]

slice()

Returns a map with the slice from the original map.

public function slice( int $offset, int $length = null ) : self

The rules for offsets are:

Similar for the length:

The keys of the items returned in the new map are the same as in the original one.

Examples:

Map::from( ['a', 'b', 'c'] )->slice( 1 );
// ['b', 'c']

Map::from( ['a', 'b', 'c'] )->slice( 1, 1 );
// ['b']

Map::from( ['a', 'b', 'c', 'd'] )->slice( -2, -1 );
// ['c']

some()

Tests if at least one element passes the test or is part of the map.

public function some( $values, bool $strict = false ) : bool

Examples:

Map::from( ['a', 'b'] )->some( 'a' );
// true

Map::from( ['a', 'b'] )->some( ['a', 'c'] );
// true

Map::from( ['a', 'b'] )->some( function( $item, $key ) {
    return $item === 'a'
} );
// true

Map::from( ['a', 'b'] )->some( ['c', 'd'] );
// false

Map::from( ['1', '2'] )->some( [2], true );
// false

sort()

Sorts all elements without maintaining the key association.

public function sort( int $options = SORT_REGULAR ) : self

The parameter modifies how the values are compared. Possible parameter values are:

The keys are NOT preserved and elements get a new index. No new map is created.

Examples:

Map::from( ['a' => 1, 'b' => 0] )->sort();
// [0 => 0, 1 => 1]

Map::from( [0 => 'b', 1 => 'a'] )->sort();
// [0 => 'a', 1 => 'b']

splice()

Removes a portion of the map and replace it with the given replacement, then return the updated map.

public function splice( int $offset, int $length = null, $replacement = [] ) : self

The rules for offsets are:

Similar for the length:

Numerical array indexes are NOT preserved.

Examples:

Map::from( ['a', 'b', 'c'] )->splice( 1 );
// ['b', 'c'] and map contains ['a']

Map::from( ['a', 'b', 'c'] )->splice( 1, 1, ['x', 'y'] );
// ['b'] and map contains ['a', 'x', 'y', 'c']

strAfter()

Returns the strings after the passed value.

public function strAfter( string $value, bool $case = false, string $encoding = 'UTF-8' ) : self

All scalar values (bool, int, float, string) will be converted to strings. Non-scalar values as well as empty strings will be skipped and are not part of the result.

Examples:

Map::from( ['äöüß'] )->strAfter( 'ö' );
// ['üß']

Map::from( ['abc'] )->strAfter( '' );
// ['abc']

Map::from( ['abc'] )->strAfter( 'b' );
// ['c']

Map::from( ['abc'] )->strAfter( 'c' );
// ['']

Map::from( ['abc'] )->strAfter( 'x' )
// []

Map::from( [''] )->strAfter( '' );
// []

Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strAfter( '' );
// ['1', '1', '1']

Map::from( [0, 0.0, false, []] )->strAfter( '' );
// ['0', '0']

strBefore()

Returns the strings before the passed value.

public function strBefore( string $value, bool $case = false, string $encoding = 'UTF-8' ) : self

All scalar values (bool, int, float, string) will be converted to strings. Non-scalar values as well as empty strings will be skipped and are not part of the result.

Examples:

Map::from( ['äöüß'] )->strBefore( 'ü' );
// ['äö']

Map::from( ['abc'] )->strBefore( '' );
// ['abc']

Map::from( ['abc'] )->strBefore( 'b' );
// ['a']

Map::from( ['abc'] )->strBefore( 'a' );
// ['']

Map::from( ['abc'] )->strBefore( 'x' )
// []

Map::from( [''] )->strBefore( '' );
// []

Map::from( [1, 1.0, true, ['x'], new \stdClass] )->strBefore( '' );
// ['1', '1', '1']

Map::from( [0, 0.0, false, []] )->strBefore( '' );
// ['0', '0']

strContains()

Tests if at least one of the passed strings is part of at least one entry.

public function strContains( $value, string $encoding = 'UTF-8' ) : bool

Examples:

Map::from( ['abc'] )->strContains( '' );
// true

Map::from( ['abc'] )->strContains( 'a' );
// true

Map::from( ['abc'] )->strContains( 'bc' );
// true

Map::from( [12345] )->strContains( '23' );
// true

Map::from( [123.4] )->strContains( 23.4 );
// true

Map::from( [12345] )->strContains( false );
// true ('12345' contains '')

Map::from( [12345] )->strContains( true );
// true ('12345' contains '1')

Map::from( [false] )->strContains( false );
// true  ('' contains '')

Map::from( [''] )->strContains( false );
// true ('' contains '')

Map::from( ['abc'] )->strContains( ['b', 'd'] );
// true

Map::from( ['abc'] )->strContains( 'c', 'ASCII' );
// true

Map::from( ['abc'] )->strContains( 'd' );
// false

Map::from( ['abc'] )->strContains( 'cb' );
// false

Map::from( [23456] )->strContains( true );
// false ('23456' doesn't contain '1')

Map::from( [false] )->strContains( 0 );
// false ('' doesn't contain '0')

Map::from( ['abc'] )->strContains( ['d', 'e'] );
// false

Map::from( ['abc'] )->strContains( 'cb', 'ASCII' );
// false

strContainsAll()

Tests if all of the entries contains one of the passed strings.

public function strContainsAll( $value, string $encoding = 'UTF-8' ) : bool

Examples:

Map::from( ['abc', 'def'] )->strContainsAll( '' );
// true

Map::from( ['abc', 'cba'] )->strContainsAll( 'a' );
// true

Map::from( ['abc', 'bca'] )->strContainsAll( 'bc' );
// true

Map::from( [12345, '230'] )->strContainsAll( '23' );
// true

Map::from( [123.4, 23.42] )->strContainsAll( 23.4 );
// true

Map::from( [12345, '234'] )->strContainsAll( [true, false] );
// true ('12345' contains '1' and '234' contains '')

Map::from( ['', false] )->strContainsAll( false );
// true ('' contains '')

Map::from( ['abc', 'def'] )->strContainsAll( ['b', 'd'] );
// true

Map::from( ['abc', 'ecf'] )->strContainsAll( 'c', 'ASCII' );
// true

Map::from( ['abc', 'def'] )->strContainsAll( 'd' );
// false

Map::from( ['abc', 'cab'] )->strContainsAll( 'cb' );
// false

Map::from( [23456, '123'] )->strContains( true );
// false ('23456' doesn't contain '1')

Map::from( [false, '000'] )->strContains( 0 );
// false ('' doesn't contain '0')

Map::from( ['abc', 'acf'] )->strContainsAll( ['d', 'e'] );
// false

Map::from( ['abc', 'bca'] )->strContainsAll( 'cb', 'ASCII' );
// false

strEnds()

Tests if at least one of the entries ends with one of the passed strings.

public function strEnds( $value, string $encoding = 'UTF-8' ) : bool

Examples:

Map::from( ['abc'] )->strEnds( '' );
// true

Map::from( ['abc'] )->strEnds( 'c' );
// true

Map::from( ['abc'] )->strEnds( 'bc' );
// true

Map::from( ['abc'] )->strEnds( ['b', 'c'] );
// true

Map::from( ['abc'] )->strEnds( 'c', 'ASCII' );
// true

Map::from( ['abc'] )->strEnds( 'a' );
// false

Map::from( ['abc'] )->strEnds( 'cb' );
// false

Map::from( ['abc'] )->strEnds( ['d', 'b'] );
// false

Map::from( ['abc'] )->strEnds( 'cb', 'ASCII' );
// false

strEndsAll()

Tests if all of the entries ends with at least one of the passed strings.

public function strEndsAll( $value, string $encoding = 'UTF-8' ) : bool

Examples:

Map::from( ['abc', 'def'] )->strEndsAll( '' );
// true

Map::from( ['abc', 'bac'] )->strEndsAll( 'c' );
// true

Map::from( ['abc', 'cbc'] )->strEndsAll( 'bc' );
// true

Map::from( ['abc', 'def'] )->strEndsAll( ['c', 'f'] );
// true

Map::from( ['abc', 'efc'] )->strEndsAll( 'c', 'ASCII' );
// true

Map::from( ['abc', 'fed'] )->strEndsAll( 'd' );
// false

Map::from( ['abc', 'bca'] )->strEndsAll( 'ca' );
// false

Map::from( ['abc', 'acf'] )->strEndsAll( ['a', 'c'] );
// false

Map::from( ['abc', 'bca'] )->strEndsAll( 'ca', 'ASCII' );
// false

string()

Returns an element by key and casts it to string if possible.

public function string( $key, $default = '' ) : string

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:

Map::from( ['a' => true] )->string( 'a' );
// '1'

Map::from( ['a' => 1] )->string( 'a' );
// '1'

Map::from( ['a' => 1.1] )->string( 'a' );
// '1.1'

Map::from( ['a' => 'abc'] )->string( 'a' );
// 'abc'

Map::from( ['a' => ['b' => ['c' => 'yes']]] )->string( 'a/b/c' );
// 'yes'

Map::from( [] )->string( 'c', function() { return 'no'; } );
// 'no'

Map::from( [] )->string( 'b' );
// ''

Map::from( ['b' => ''] )->string( 'b' );
// ''

Map::from( ['b' => null] )->string( 'b' );
// ''

Map::from( ['b' => [true]] )->string( 'b' );
// ''

Map::from( ['b' => '#resource'] )->string( 'b' );
// '' (resources are not scalar)

Map::from( ['b' => new \stdClass] )->string( 'b' );
// '' (objects are not scalar)

Map::from( [] )->string( 'c', new \Exception( 'error' ) );
// throws exception

strLower()

Converts all alphabetic characters in strings to lower case.

public function strLower( string $encoding = 'UTF-8' ) : self

Examples:

Map::from( ['My String'] )->strLower();
// ["my string"]

Map::from( ['Τάχιστη'] )->strLower();
// ["τάχιστη"]

Map::from( ['Äpfel', 'Birnen'] )->strLower( 'ISO-8859-1' );
// ["äpfel", "birnen"]

strReplace()

Replaces all occurrences of the search string with the replacement string.

public function strReplace( $search, $replace, bool $case = false ) : self

If you use an array of strings for search or search/replacement, the order of the strings matters! Each search string found is replaced by the corresponding replacement string at the same position.

In case of array parameters and if the number of replacement strings is less than the number of search strings, the search strings with no corresponding replacement string are replaced with empty strings. Replacement strings with no corresponding search string are ignored.

An array parameter for the replacements is only allowed if the search parameter is an array of strings too!

Because the method replaces from left to right, it might replace a previously inserted value when doing multiple replacements. Entries which are non-string values are left untouched.

Examples:

Map::from( ['google.com', 'aimeos.com'] )->strReplace( '.com', '.de' );
// ['google.de', 'aimeos.de']

Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], '.de' );
// ['google.de', 'aimeos.de']

Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], ['.de'] );
// ['google.de', 'aimeos']

Map::from( ['google.com', 'aimeos.org'] )->strReplace( ['.com', '.org'], ['.fr', '.de'] );
// ['google.fr', 'aimeos.de']

Map::from( ['google.com', 'aimeos.com'] )->strReplace( ['.com', '.co'], ['.co', '.de', '.fr'] );
// ['google.de', 'aimeos.de']

Map::from( ['google.com', 'aimeos.com', 123] )->strReplace( '.com', '.de' );
// ['google.de', 'aimeos.de', 123]

Map::from( ['GOOGLE.COM', 'AIMEOS.COM'] )->strReplace( '.com', '.de', true );
// ['GOOGLE.de', 'AIMEOS.de']

strStarts()

Tests if at least one of the entries starts with at least one of the passed strings.

public function strStarts( $value, string $encoding = 'UTF-8' ) : bool

Examples:

Map::from( ['abc'] )->strStarts( '' );
// true

Map::from( ['abc'] )->strStarts( 'a' );
// true

Map::from( ['abc'] )->strStarts( 'ab' );
// true

Map::from( ['abc'] )->strStarts( ['a', 'b'] );
// true

Map::from( ['abc'] )->strStarts( 'ab', 'ASCII' );
// true

Map::from( ['abc'] )->strStarts( 'b' );
// false

Map::from( ['abc'] )->strStarts( 'bc' );
// false

Map::from( ['abc'] )->strStarts( ['b', 'c'] );
// false

Map::from( ['abc'] )->strStarts( 'bc', 'ASCII' );
// false

strStartsAll()

Tests if all of the entries starts with one of the passed strings.

public function strStartsAll( $value, string $encoding = 'UTF-8' ) : bool

Examples:

Map::from( ['abc', 'def'] )->strStartsAll( '' );
// true

Map::from( ['abc', 'acb'] )->strStartsAll( 'a' );
// true

Map::from( ['abc', 'aba'] )->strStartsAll( 'ab' );
// true

Map::from( ['abc', 'def'] )->strStartsAll( ['a', 'd'] );
// true

Map::from( ['abc', 'acf'] )->strStartsAll( 'a', 'ASCII' );
// true

Map::from( ['abc', 'def'] )->strStartsAll( 'd' );
// false

Map::from( ['abc', 'bca'] )->strStartsAll( 'ab' );
// false

Map::from( ['abc', 'bac'] )->strStartsAll( ['a', 'c'] );
// false

Map::from( ['abc', 'cab'] )->strStartsAll( 'ab', 'ASCII' );
// false

strUpper()

Converts all alphabetic characters in strings to upper case.

public function strUpper( string $encoding = 'UTF-8' ) :self

Examples:

Map::from( ['My String'] )->strUpper();
// ["MY STRING"]

Map::from( ['τάχιστη'] )->strUpper();
// ["ΤΆΧΙΣΤΗ"]

Map::from( ['äpfel', 'birnen'] )->strUpper( 'ISO-8859-1' );
// ["ÄPFEL", "BIRNEN"]

suffix

Adds a suffix at the end of each map entry.

public function suffix( $suffix, int $depth = null ) : self

By defaul, nested arrays are walked recusively so all entries at all levels are suffixed. The keys are preserved using this method.

Examples:

Map::from( ['a', 'b'] )->suffix( '-1' );
// ['a-1', 'b-1']

Map::from( ['a', ['b']] )->suffix( '-1' );
// ['a-1', ['b-1']]

Map::from( ['a', ['b']] )->suffix( '-1', 1 );
// ['a-1', ['b']]

Map::from( ['a', 'b'] )->suffix( function( $item, $key ) {
    return '-' . ( ord( $item ) + ord( $key ) );
} );
// ['a-145', 'b-147']

sum()

Returns the sum of all integer and float values in the map.

public function sum( string $col = null ) : float

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:

Map::from( [1, 3, 5] )->sum();
// 9

Map::from( [1, 'sum', 5] )->sum();
// 6

Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->sum( 'p' );
// 90

Map::from( [['i' => ['p' => 30]], ['i' => ['p' => 50]]] )->sum( 'i/p' );
// 80

take()

Returns a new map with the given number of items.

public function take( int $size, $offset = 0 ) : self

The keys of the items returned in the new map are the same as in the original one.

Examples:

Map::from( [1, 2, 3, 4] )->take( 2 );
// [0 => 1, 1 => 2]

Map::from( [1, 2, 3, 4] )->take( 2, 1 );
// [1 => 2, 2 => 3]

Map::from( [1, 2, 3, 4] )->take( 2, -2 );
// [2 => 3, 3 => 4]

Map::from( [1, 2, 3, 4] )->take( 2, function( $item, $key ) {
    return $item < 2;
} );
// [1 => 2, 2 => 3]

tap()

Passes a clone of the map to the given callback.

public function tap( callable $callback ) : self

Use it to "tap" into a chain of methods to check the state between two method calls. The original map is not altered by anything done in the callback.

Examples:

Map::from( [3, 2, 1] )->rsort()->tap( function( $map ) {
    print_r( $map->remove( 0 )->toArray() );
} )->first();
// 1

It will sort the list in reverse order([1, 2, 3]), then prints the items ([2, 3]) without the first one in the function passed to tap() and returns the first item ("1") at the end.

times()

Creates a new map by invoking the closure the given number of times.

public static function times( int $num, \Closure $callback ) : self

This method creates a lazy Map and the entries are generated after calling another method that operates on the Map contents. Thus, the passed callback is not called immediately!

Examples:

Map::times( 3, function( $num ) {
    return $num * 10;
} );
// [0 => 0, 1 => 10, 2 => 20]

Map::times( 3, function( $num, &$key ) {
    $key = $num * 2;
    return $num * 5;
} );
// [0 => 0, 2 => 5, 4 => 10]

Map::times( 2, function( $num ) {
    return new \stdClass();
} );
// [0 => new \stdClass(), 1 => new \stdClass()]

toArray()

Returns the elements as a plain array.

public function toArray() : array

Examples:

Map::from( ['a'] )->toArray();
// ['a']

toJson()

Returns the elements encoded as JSON string.

public function toJson( int $options = 0 ) : ?string

There are several options available to modify the JSON string which are described in the PHP json_encode() manual. The parameter can be a single JSON_* constant or a bitmask of several constants combine by bitwise OR (|), e.g.:

JSON_FORCE_OBJECT|JSON_HEX_QUOT

Examples:

Map::from( ['a', 'b'] )->toJson();
// '["a","b"]'

Map::from( ['a' => 'b'] )->toJson();
// '{"a":"b"}'

Map::from( ['a', 'b'] )->toJson( JSON_FORCE_OBJECT );
// '{"0":"a", "1":"b"}'

toUrl()

Creates a HTTP query string from the map elements.

public function toUrl() : string

Examples:

Map::from( ['a' => 1, 'b' => 2] )->toUrl();
// a=1&b=2

Map::from( ['a' => ['b' => 'abc', 'c' => 'def'], 'd' => 123] )->toUrl();
// a%5Bb%5D=abc&a%5Bc%5D=def&d=123

transpose()

Exchanges rows and columns for a two dimensional map.

public function transpose() : self

Examples:

Map::from( [
  ['name' => 'A', 2020 => 200, 2021 => 100, 2022 => 50],
  ['name' => 'B', 2020 => 300, 2021 => 200, 2022 => 100],
  ['name' => 'C', 2020 => 400, 2021 => 300, 2022 => 200],
] )->transpose();
/*
[
  'name' => ['A', 'B', 'C'],
  2020 => [200, 300, 400],
  2021 => [100, 200, 300],
  2022 => [50, 100, 200]
]
*/

Map::from( [
  ['name' => 'A', 2020 => 200, 2021 => 100, 2022 => 50],
  ['name' => 'B', 2020 => 300, 2021 => 200],
  ['name' => 'C', 2020 => 400]
] );
/*
[
  'name' => ['A', 'B', 'C'],
  2020 => [200, 300, 400],
  2021 => [100, 200],
  2022 => [50]
]
*/

traverse()

Traverses trees of nested items passing each item to the callback.

public function traverse( \Closure $callback = null, string $nestKey = 'children' ) : self

This does work for nested arrays and objects with public properties or objects implementing __isset() and __get() methods. To build trees of nested items, use the tree() method.

Examples:

Map::from( [[
  'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
    ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
    ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
  ]
]] )->traverse();
/*
[
  ['id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [...]],
  ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
  ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []],
]
*/

Map::from( [[
  'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
    ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
    ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
  ]
]] )->traverse( function( $entry, $key, $level ) {
  return str_repeat( '-', $level ) . '- ' . $entry['name'];
} );
// ['- n1', '-- n2', '-- n3']

Map::from( [[
  'id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [
    ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => []],
    ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => []]
  ]
]] )->traverse( function( &$entry, $key, $level, $parent ) {
  $entry['path'] = isset( $parent['path'] ) ? $parent['path'] . '/' . $entry['name'] : $entry['name'];
  return $entry;
} );
/*
[
  ['id' => 1, 'pid' => null, 'name' => 'n1', 'children' => [...], 'path' => 'n1'],
  ['id' => 2, 'pid' => 1, 'name' => 'n2', 'children' => [], 'path' => 'n1/n2'],
  ['id' => 3, 'pid' => 1, 'name' => 'n3', 'children' => [], 'path' => 'n1/n3'],
]
*/

Map::from( [[
  'id' => 1, 'pid' => null, 'name' => 'n1', 'nodes' => [
    ['id' => 2, 'pid' => 1, 'name' => 'n2', 'nodes' => []]
  ]
]] )->traverse( null, 'nodes' );
/*
[
  ['id' => 1, 'pid' => null, 'name' => 'n1', 'nodes' => [...]],
  ['id' => 2, 'pid' => 1, 'name' => 'n2', 'nodes' => []],
]
*/

tree()

Creates a tree structure from the list items.

public function tree( string $idKey, string $parentKey, string $nestKey = 'children' ) : self

Use this method to rebuild trees e.g. from database records. To traverse trees, use the traverse() method.

Examples:

Map::from( [
  ['id' => 1, 'pid' => null, 'lvl' => 0, 'name' => 'n1'],
  ['id' => 2, 'pid' => 1, 'lvl' => 1, 'name' => 'n2'],
  ['id' => 3, 'pid' => 2, 'lvl' => 2, 'name' => 'n3'],
  ['id' => 4, 'pid' => 1, 'lvl' => 1, 'name' => 'n4'],
  ['id' => 5, 'pid' => 3, 'lvl' => 2, 'name' => 'n5'],
  ['id' => 6, 'pid' => 1, 'lvl' => 1, 'name' => 'n6'],
] )->tree( 'id', 'pid' );
/*
[1 => [
  'id' => 1, 'pid' => null, 'lvl' => 0, 'name' => 'n1', 'children' => [
    2 => ['id' => 2, 'pid' => 1, 'lvl' => 1, 'name' => 'n2', 'children' => [
      3 => ['id' => 3, 'pid' => 2, 'lvl' => 2, 'name' => 'n3', 'children' => []]
    ]],
    4 => ['id' => 4, 'pid' => 1, 'lvl' => 1, 'name' => 'n4', 'children' => [
      5 => ['id' => 5, 'pid' => 3, 'lvl' => 2, 'name' => 'n5', 'children' => []]
    ]],
    6 => ['id' => 6, 'pid' => 1, 'lvl' => 1, 'name' => 'n6', 'children' => []]
  ]
]]
*/

To build the tree correctly, the items must be in order or at least the nodes of the lower levels must come first. For a tree like this:

n1
|- n2
|  |- n3
|- n4
|  |- n5
|- n6

Accepted item order:

If your items are unordered, apply usort() first to the map entries, e.g.

Map::from( [['id' => 3, 'lvl' => 2], ...] )->usort( function( $item1, $item2 ) {
  return $item1['lvl'] <=> $item2['lvl'];
} );

trim()

Removes the passed characters from the left/right of all strings.

public function trim( string $chars = " \n\r\t\v\x00" ) : self

Examples:

Map::from( [" abc\n", "\tcde\r\n"] )->trim();
// ["abc", "cde"]

Map::from( ["a b c", "cbax"] )->trim( 'abc' );
// [" b ", "x"]

uasort()

Sorts all elements using a callback and maintains the key association.

public function uasort( callable $callback ) : self

The given callback will be used to compare the values. The callback must accept two parameters (item A and B) and must return -1 if item A is smaller than item B, 0 if both are equal and 1 if item A is greater than item B. Both, a method name and an anonymous function can be passed.

The keys are preserved using this method and no new map is created.

Examples:

Map::from( ['a' => 'B', 'b' => 'a'] )->uasort( 'strcasecmp' );
// ['b' => 'a', 'a' => 'B']

Map::from( ['a' => 'B', 'b' => 'a'] )->uasort( function( $itemA, $itemB ) {
    return strtolower( $itemA ) <=> strtolower( $itemB );
} );
// ['b' => 'a', 'a' => 'B']

uksort()

Sorts the map elements by their keys using a callback.

public function uksort( callable $callback ) : self

The given callback will be used to compare the keys. The callback 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.

The keys are preserved using this method and no new map is created.

Examples:

Map::from( ['B' => 'a', 'a' => 'b'] )->uksort( 'strcasecmp' );
// ['a' => 'b', 'B' => 'a']

Map::from( ['B' => 'a', 'a' => 'b'] )->uksort( function( $keyA, $keyB ) {
    return strtolower( $keyA ) <=> strtolower( $keyB );
} );
// ['a' => 'b', 'B' => 'a']

union()

Builds a union of the elements and the given elements without returning a new map. Existing keys in the map will not be overwritten

public function union( iterable $elements ) : self

If list entries should be overwritten, use merge() instead. The keys are preserved using this method and no new map is created.

Examples:

Map::from( [0 => 'a', 1 => 'b'] )->union( [0 => 'c'] );
// [0 => 'a', 1 => 'b'] because the key 0 isn't overwritten

Map::from( ['a' => 1, 'b' => 2] )->union( ['c' => 1] );
// ['a' => 1, 'b' => 2, 'c' => 1]

unique()

Returns only unique elements from the map in a new map

public function unique( string $key = null ) : self

Two elements are considered equal if comparing their string representions returns TRUE:

(string) $elem1 === (string) $elem2

The keys of the elements are only preserved in the new map if no key is passed.

Examples:

Map::from( [0 => 'a', 1 => 'b', 2 => 'b', 3 => 'c'] )->unique();
// [0 => 'a', 1 => 'b', 3 => 'c']

Map::from( [['p' => '1'], ['p' => 1], ['p' => 2]] )->unique( 'p' );
// [['p' => 1], ['p' => 2]]

Map::from( [['i' => ['p' => '1']], ['i' => ['p' => 1]]] )->unique( 'i/p' );
// [['i' => ['p' => '1']]]

unshift()

Pushes an element onto the beginning of the map without returning a new map.

public function unshift( $value, $key = null ) : self

The keys of the elements are only preserved in the new map if no key is passed.

Examples:

Map::from( ['a', 'b'] )->unshift( 'd' );
// ['d', 'a', 'b']

Map::from( ['a', 'b'] )->unshift( 'd', 'first' );
// ['first' => 'd', 0 => 'a', 1 => 'b']

Performance note:

The bigger the list, the higher the performance impact because unshift() needs to create a new list and copies all existing elements to the new array. Usually, it's better to push() new entries at the end and reverse() the list afterwards:

$map->push( 'a' )->push( 'b' )->reverse();

instead of

$map->unshift( 'a' )->unshift( 'b' );

usort()

Sorts all elements using a callback without maintaining the key association.

public function usort( callable $callback ) : self

The given callback will be used to compare the values. The callback must accept two parameters (item A and B) and must return -1 if item A is smaller than item B, 0 if both are equal and 1 if item A is greater than item B. Both, a method name and an anonymous function can be passed.

The keys are NOT preserved and elements get a new index. No new map is created.

Examples:

Map::from( ['a' => 'B', 'b' => 'a'] )->usort( 'strcasecmp' );
// [0 => 'a', 1 => 'B']

Map::from( ['a' => 'B', 'b' => 'a'] )->usort( function( $itemA, $itemB ) {
    return strtolower( $itemA ) <=> strtolower( $itemB );
} );
// [0 => 'a', 1 => 'B']

values()

Resets the keys and return the values in a new map.

public function values() : self

Examples:

Map::from( ['x' => 'b', 2 => 'a', 'c'] )->values();
// [0 => 'b', 1 => 'a', 2 => 'c']

walk()

Applies the given callback to all elements.

public function walk( callable $callback, $data = null, bool $recursive = true ) : self

To change the values of the Map, specify the value parameter as reference (&$value). You can only change the values but not the keys nor the array structure.

By default, Map elements which are arrays will be traversed recursively. To iterate over the Map elements only, pass FALSE as third parameter.

Examples:

Map::from( ['a', 'B', ['c', 'd'], 'e'] )->walk( function( &$value ) {
    $value = strtoupper( $value );
} );
// ['A', 'B', ['C', 'D'], 'E']

Map::from( [66 => 'B', 97 => 'a'] )->walk( function( $value, $key ) {
    echo 'ASCII ' . $key . ' is ' . $value . "\n";
} );
/*
ASCII 66 is B
ASCII 97 is a
*/

Map::from( [1, 2, 3] )->walk( function( &$value, $key, $data ) {
    $value = $data[$value] ?? $value;
}, [1 => 'one', 2 => 'two'] );
// ['one', 'two', 3]

where()

Filters the list of elements by a given condition.

public function where( string $key, string $op, $value ) : self

Available operators are:

The keys of the original map are preserved in the returned map.

Examples:

Map::from( [
  ['id' => 1, 'type' => 'name'],
  ['id' => 2, 'type' => 'short'],
] )->where( 'type', '==', 'name' );
/*
[
    ['id' => 1, 'type' => 'name']
]
*/

Map::from( [
  ['id' => 3, 'price' => 10],
  ['id' => 4, 'price' => 50],
] )->where( 'price', '>', 20 );
/*
[
    ['id' => 4, 'price' => 50]
]
*/

Map::from( [
  ['id' => 3, 'price' => 10],
  ['id' => 4, 'price' => 50],
] )->where( 'price', 'in', [10, 25] );
/*
[
    ['id' => 3, 'price' => 10]
]
*/

Map::from( [
  ['id' => 3, 'price' => 10],
  ['id' => 4, 'price' => 50],
] )->where( 'price', '-', [10, 100] );
/*
[
    ['id' => 3, 'price' => 10],
    ['id' => 4, 'price' => 50]
]
*/

Map::from( [
  ['item' => ['id' => 3, 'price' => 10]],
  ['item' => ['id' => 4, 'price' => 50]],
] )->where( 'item/price', '>', 30 );
/*
[
    ['id' => 4, 'price' => 50]
]
*/

with()

Returns a copy of the map with the element at the given index replaced with the given value.

public function with( $key, $value ) : self

The original map stays untouched! This method is a shortcut for calling the set() methods.

Examples:

$m = Map::from( ['a' => 1] );

$m->with( 2, 'b' );
// ['a' => 1, 2 => 'b']

$m->with( 'a', 2 );
// ['a' => 2]

$m->all();
// ['a' => 1]

zip()

Merges the values of all arrays at the corresponding index.

public function zip( $array1, ... ) : self

Examples:

Map::from( [1, 2, 3] )->zip( ['one', 'two', 'three'], ['uno', 'dos', 'tres'] );
/*
[
    [1, 'one', 'uno'],
    [2, 'two', 'dos'],
    [3, 'three', 'tres'],
]
*/

Custom methods

Most of the time, it's enough to pass an anonymous function to the pipe() method to implement custom functionality in map objects:

Map::from( ['a', 'b'] )->pipe( function( $map ) {
    return strrev( $map->join( '-' ) );
} );

If you need some functionality more often and at different places in your source code, than it's better to register a custom method once and only call it everywhere:

Map::method( 'strrev', function( $sep ) {
    return strrev( join( '-', $this->list() ) );
} );
Map::from( ['a', 'b'] )->strrev( '-' );

Make sure, you register the method before using it. You can pass arbitrary parameters to your function and it has access to the internas of the map. Thus, your function can use $this to call all available methods:

Map::method( 'notInBoth', function( iterable $elements ) {
    return new self( $this->diff( $elements ) + Map::from( $elements )->diff( $this->items ) );
} );

Your custom method has access to $this->items array which contains the map elements and can also use the internal $this->getArray( iterable $list ) method to convert iterable parameters (arrays, generators and objects implementing \Traversable) to plain arrays:

Map::method( 'mycombine', function( iterable $keys ) {
    return new self( array_combine( $this->getArray( $keys ), $this-items ) );
} );

Performance

The performance most methods only depends on the array_* function that are used internally by the Map class. If the methods of the Map class contains additional code, it's optimized to be as fast as possible.

Creating Map vs. array

Creating an map object with an array instead of creating a plain array only is significantly slower (ca. 10x) but in absolute values we are talking about nano seconds. It will only get notable if you create 10,000 map objects instead of 10,000 arrays. Then, creating maps will last ca. 10ms longer.

Usually, this isn't much of a problem because applications create arrays with lots of elements instead of 10,000+ arrays. Nevertheless, if your application creates a very large number of arrays within one area, you should think about avoiding map objects in that area.

If you use the Map::from() to create map objects, then be aware that this adds another function call. Using these methods for creating the map object lasts around 1.1x resp. 1.3x compared to the time for new Map().

Conclusion: Using new Map() is fastest and map() is faster than Map::from().

Populating Map vs. array

Adding an element to a Map object using $map[] = 'a' is ca. 5x slower than doing the same on a plain array. This is because the method offsetSet() will be called instead of adding the new element to the array directly. This applies to the $map->push( 'a' ) method too.

When creating arrays in loops, you should populate the array first and then create a Map object from the the array:

$list = [];
for( $i = 0; $i < 1000; $i++ ) {
    $list[] = $i;
}
$map = map( $list );

The array is NOT copied when creating the Map object so there's virtually no performance loss using the Map afterwards.

Using Map methods vs. language constructs

Language constructs such as empty(), count() or isset() are faster than calling a method and using $map->isEmpty() or $map->count() is ca. 4x slower.

Again, we are talking about nano seconds. For 10,000 calls to empty( $array ) compared to $map->isEmpty(), the costs are around 4ms in total.

Using Map methods vs. array_* functions

Using the Map methods instead of the array* functions adds an additional method call. Internally, the Map objects uses the same array* functions but offers a much more usable interface.

The time for the additional method call is almost neglectable because the array_* methods needs much longer to perform the operation on the array elements depending on the size of the array.

Using anonymous functions

Several Map methods support passing an anonymous function that is applied to every element of the map. PHP needs some time to call the passed function and to execute its code. Depending on the number of elements, this may have a significant impact on performance!

The pipe() method of the Map object is an exception because it receives the whole map object instead of each element separately. Its performance mainly depends on the implemented code:

$map->pipe( function( Map $map ) {
    // perform operations on the map
} );

Using shift() and unshift()

Both methods are costly, especially on large arrays. The used array_shift() and array_unshift() functions will reindex all numerical keys of the array.

If you want to reduce or create a large list of elements from the beginning in an iterative way, you should use push() instead of prepend():

$map->reverse()->pop(); // use pop() until it returns NULL
$map->push( 'z' )->push( 'y' )->push( 'x' )->reverse(); // use push() for adding

Upgrade guide

2.x -> 3.x

Use list() method

When adding own methods to the Map object, don't access the $this->list class variable directly. It's not guaranteed to be an array any more but will store the value passed to the Map constructor. Instead, use the `list() method to get a reference to the array of elements:

$this->list();

As it's a reference to the array of elements, you can modify it directly or even use PHP functions that require a variable reference:

$this->list()[] = 123;
reset( $this->list() );

Renamed internal methods

Two internal methods have been renamed and you have to use their new name if you have added own methods to the Map object:

// instead of $this->getArray( $array )
$this->array( $array )

 // instead of $this->getValue( $entry, array $parts )
$this->val( $entry, array $parts )

1.x -> 2.x

jQuery style method calls

You can call methods of objects in a map like this:

// 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();

Before, it was checked if the objects really implement setStatus() and getCode().

This isn't the case any more to avoid returning an empty map if the method name is wrong or the called method is implemented using the __call() magic method. Now, PHP generates a fatal error if the method isn't implemented by all objects.

Second equals() parameter

The second parameter of the equals() method ($assoc) to compare keys too has been removed. Use the is() method instead:

// 1.x
map( ['one' => 1] )->equals( ['one' => 1], true );

// 2.x
map( ['one' => 1] )->is( ['one' => 1] );

New find() argument

A default value or exception object can be passed to the find() method now as second argument. The $reverse argument has been moved to the third position.

// 1.x
Map::from( ['a', 'c', 'e'] )->find( function( $value, $key ) {
    return $value >= 'b';
}, true );

// 2.x
Map::from( ['a', 'c', 'e'] )->find( function( $value, $key ) {
    return $value >= 'b';
}, null, true );

groupBy() semantic change

If the key passed to groupBy() didn't exist, the items have been grouped using the given key. Now, an empty string is used as key to offer easier checking and sorting of the keys.

Map::from( [
    10 => ['aid' => 123, 'code' => 'x-abc'],
] )->groupBy( 'xid' );

// 1.x
[
    'xid' => [
        10 => ['aid' => 123, 'code' => 'x-abc']
    ]
]

// 2.x
[
    '' => [
        10 => ['aid' => 123, 'code' => 'x-abc']
    ]
]

offsetExists() semantic change

To be consistent with typical PHP behavior, the offsetExists() method use isset() instead of array_key_exists() now. This changes the behavior when dealing with NULL values.

$m = Map::from( ['foo' => null] );

// 1.x
isset( $m['foo'] ); // true

// 2.x
isset( $m['foo'] ); // false

Renamed split() method

The static Map::split() method has been renamed to Map::explode() and the argument order has changed. This avoids conflicts with the Laravel split() method and is in line with the PHP explode() method.

// 1.x
Map::split( 'a,b,c', ',' );

// 2.x
Map::explode( ',', 'a,b,c' );

All versions of map with dependencies

PHP Build Version
Package Version
Requires php Version ^7.1||^8.0
ext-mbstring Version *
ext-pcre Version *
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package aimeos/map contains the following files

Loading the files please wait ....