Easy and elegant handling of PHP arrays by using an array-like collection object as offered by jQuery and Laravel Collections.
composer req aimeos/map
Supported PHP versions:
PHP 7.1+
PHP 8+
Table of contents
Why PHP Map
List of methods
Create
Access
Add
Aggregate
Debug
Order
Shorten
Test
Mutate
Misc
Documentation
Custom methods
Performance
Upgrade guide
Instead of:
$list = [['id' => 'one', 'value' => 'value1'], ['id' => 'two', 'value' => 'value2'], null];$list[] = ['id' => 'three', 'value' => 'value3']; // add elementunset( $list[0] ); // remove element$list = array_filter( $list ); // remove empty valuessort( $list ); // sort elements$pairs = array_column( $list, 'value', 'id' ); // create ['three' => 'value3']$value = reset( $pairs ) ?: null; // return first value
Only use:
$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:
$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.:
$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:
// 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:
['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:
['a' => 'x', 'b' => 'y']
function map function is_map __call __callStatic __construct after all arsort arsorted asort asorted at avg before bool call cast chunk clear clone col collapse combine compare concat contains copy count countBy dd delimiter diff diffAssoc diffKeys dump duplicates each empty equals every except explode filter find first firstKey flat flip float from fromJson get getIterator grep groupBy has if ifAny ifEmpty implements in includes index insertAfter insertAt insertBefore inString int intersect intersectAssoc intersectKeys is isEmpty isNumeric isObject isScalar isString join jsonSerialize keys krsort krsorted ksort 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 split strAfter strContains strContainsAll strEnds strEndsAll string strLower strReplace strStarts strStartsAll strUpper suffix sum take tap times toArray toJson toReversed toSorted toUrl transform transpose traverse tree trim uasort uasorted uksort uksorted union unique unshift usort usorted values walk where with zip
function map() : Creates a new map from passed elements
__construct() : Creates a new map
clone() : Clones the map and all objects within
copy() : Creates a new copy
explode() : Splits a string into a map of elements
from() : Creates a new map from passed elements
fromJson() : Creates a new map from a JSON string
times() : Creates a new map by invoking the closure a number of times
tree() : Creates a tree structure from the list items
__call() : Calls a custom method
__callStatic() : Calls a custom method statically
all() : Returns the plain array
at() : Returns the value at the given position
bool() : Returns an element by key and casts it to boolean
call() : Calls the given method on all items
find() : Returns the first/last matching element
first() : Returns the first element
firstKey() : Returns the first key
get() : Returns an element by key
index() : Returns the numerical index of the given key
int() : Returns an element by key and casts it to integer
float() : Returns an element by key and casts it to float
keys() : Returns all keys
last() : Returns the last element
lastKey() : Returns the last key
pop() : Returns and removes the last element
pos() : Returns the numerical index of the value
pull() : Returns and removes an element by key
random() : Returns random elements preserving keys
search() : Find the key of an element
shift() : Returns and removes the first element
string() : Returns an element by key and casts it to string
toArray() : Returns the plain array
unique() : Returns all unique elements preserving keys
values() : Returns all elements with new keys
concat() : Adds all elements with new keys
insertAfter() : Inserts the value after the given element
insertAt() : Inserts the element at the given position in the map
insertBefore() : Inserts the value before the given element
merge() : Combines elements overwriting existing ones
pad() : Fill up to the specified length with the given value
prepend() : Adds an element at the beginning (alias)
push() : Adds an element to the end
put() : Sets the given key and value in the map (alias)
set() : Overwrites or adds an element
union() : Adds the elements without overwriting existing ones
unshift() : Adds an element at the beginning
with() : Returns a copy and sets an element
avg() : Returns the average of all values
count() : Returns the total number of elements
countBy() : Counts how often the same values are in the map
max() : Returns the maximum value of all elements
min() : Returns the minium value of all elements
percentage() : Returns the percentage of all elements passing the test
sum() : Returns the sum of all values in the map
dd() : Prints the map content and terminates the script
dump() : Prints the map content
tap() : Passes a clone of the map to the given callback
arsort() : Reverse sort elements preserving keys
arsorted() : Reverse sort elements preserving keys in a copy of the map
asort() : Sort elements preserving keys
asorted() : Sort elements preserving keys in a copy of the map
krsort() : Reverse sort elements by keys
krsorted() : Reverse sort elements by keys in a copy of the map
ksort() : Sort elements by keys
order() : Orders elements by the passed keys
reverse() : Reverses the array order preserving keys
reversed() : Reverses the element order in a copy of the map
toReversed() : Reverses the element order in a copy of the map (alias)
rsort() : Reverse sort elements using new keys
rsorted() : Reverse sort elements using new keys in a copy of the map
shuffle() : Randomizes the element order
shuffled() : Randomizes the element order in a copy of the map
sort() : Sorts the elements in-place assigning new keys
sorted() : Sorts the elements in a copy of the map using new keys
toSorted() : Sorts the elements in a copy of the map using new keys (alias)
uasort() : Sorts elements preserving keys using callback
uasorted() : Sorts elements preserving keys using callback in a copy of the map
uksort() : Sorts elements by keys using callback
uksorted() : Sorts elements by keys using callback in a copy of the map
usort() : Sorts elements using callback assigning new keys
usorted() : Sorts elements using callback assigning new keys in a copy of the map
after() : Returns the elements after the given one
before() : Returns the elements before the given one
clear() : Removes all elements
diff() : Returns the elements missing in the given list
diffAssoc() : Returns the elements missing in the given list and checks keys
diffKeys() : Returns the elements missing in the given list by keys
except() : Returns a new map without the passed element keys
filter() : Applies a filter to all elements
grep() : Applies a regular expression to all elements
intersect() : Returns the elements shared
intersectAssoc() : Returns the elements shared and checks keys
intersectKeys() : Returns the elements shared by keys
nth() : Returns every nth element from the map
only() : Returns only those elements specified by the keys
pop() : Returns and removes the last element
pull() : Returns and removes an element by key
reject() : Removes all matched elements
remove() : Removes an element by key
shift() : Returns and removes the first element
skip() : Skips the given number of items and return the rest
slice() : Returns a slice of the map
take() : Returns a new map with the given number of items
where() : Filters the list of elements by a given condition
function is_map() : Tests if the variable is a map object
compare() : Compares the value against all map elements
contains() : Tests if an item exists in the map
each() : Applies a callback to each element
empty() : Tests if map is empty
equals() : Tests if map contents are equal
every() : Verifies that all elements pass the test of the given callback
has() : Tests if a key exists
if() : Executes callbacks depending on the condition
ifAny() : Executes callbacks if the map contains elements
ifEmpty() : Executes callbacks if the map is empty
in() : Tests if element is included
includes() : Tests if element is included
inString() : Tests if the item is part of the strings in the map
is() : Tests if the map consists of the same keys and values
isEmpty() : Tests if map is empty
isNumeric() : Tests if all entries are numeric values
isObject() : Tests if all entries are objects
isScalar() : Tests if all entries are scalar values.
isString() : Tests if all entries are string values.
implements() : Tests if all entries are objects implementing the interface
none() : Tests if none of the elements are part of the map
some() : Tests if at least one element is included
strContains() : Tests if at least one of the passed strings is part of at least one entry
strContainsAll() : Tests if all of the entries contains one of the passed strings
strEnds() : Tests if at least one of the entries ends with one of the passed strings
strEndsAll() : Tests if all of the entries ends with at least one of the passed strings
strStarts() : Tests if at least one of the entries starts with at least one of the passed strings
strStartsAll() : Tests if all of the entries starts with one of the passed strings
cast() : Casts all entries to the passed type
chunk() : Splits the map into chunks
col() : Creates a key/value mapping
collapse() : Collapses multi-dimensional elements overwriting elements
combine() : Combines the map elements as keys with the given values
flat() : Flattens multi-dimensional elements without overwriting elements
flip() : Exchanges keys with their values
groupBy() : Groups associative array elements or objects
join() : Returns concatenated elements as string with separator
ltrim() : Removes the passed characters from the left of all strings
map() : Applies a callback to each element and returns the results
partition() : Breaks the list into the given number of groups
pipe() : Applies a callback to the whole map
pluck() : Creates a key/value mapping (alias)
prefix() : Adds a prefix to each map entry
reduce() : Computes a single value from the map content
rekey() : Changes the keys according to the passed function
replace() : Replaces elements recursively
rtrim() : Removes the passed characters from the right of all strings
splice() : Replaces a slice by new elements
strAfter() : Returns the strings after the passed value
strLower() : Converts all alphabetic characters to lower case
strReplace() : Replaces all occurrences of the search string with the replacement string
strUpper() : Converts all alphabetic characters to upper case
suffix() : Adds a suffix to each map entry
toJson() : Returns the elements in JSON format
toUrl() : Creates a HTTP query string
transfrom() : Applies a callback to each element which creates new key/value pairs
transpose() : Exchanges rows and columns for a two dimensional map
traverse() : Traverses trees of nested items passing each item to the callback
trim() : Removes the passed characters from the left/right of all strings
walk() : Applies the given callback to all elements
zip() : Merges the values of all arrays at the corresponding index
delimiter() : Sets or returns the seperator for paths to multi-dimensional arrays
getIterator() : Returns an iterator for the elements
jsonSerialize() : Specifies the data which should be serialized to JSON
method() : Registers a custom method
offsetExists() : Checks if the key exists
offsetGet() : Returns an element by key
offsetSet() : Overwrites an element
offsetUnset() : Removes an element by key
sep() : Sets the seperator for paths to multi-dimensional arrays in the current map
Tests if the variable is a map object
function is_map( $var ) : bool
@param mixed $var
Variable to test
Examples:
is_map( new Map() );// trueis_map( [] );// false
Returns a new map for the passed elements.
function map( $elements = [] ) : AimeosMap
@param mixed $elements
List of elements or single value
@return AimeosMap Map instance
Examples:
// arraymap( [] );// nullmap( null );// scalarmap( 'a' );// objectmap( new stdClass() );// map objectmap( new Map() );// iterable objectmap( new ArrayObject() );// closure evaluated lazilymap( function() {return []; } );
See also:
rekey() - Changes the keys according to the passed function
transform() - Creates new key/value pairs using the passed function and returns a new map for the result
Creates a new map object.
public function __construct( $elements = [] )
@param mixed $elements
Single element, list of elements, Map object, iterable objects or iterators, everything else
Examples:
// arraynew Map( [] );// nullnew Map( null );// scalarnew Map( 'a' );// objectnew Map( new stdClass() );// map objectnew Map( new Map() );// iterable objectnew Map( new ArrayObject() );// closure evaluated lazilynew Map( function() {return []; } );
Handles dynamic calls to custom methods for the class.
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(). The called method
has access to the internal array by using $this->items
.
Examples:
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:
$item = new MyClass(); // with method setStatus() (returning $this) and getCode() implementedMap::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.
Handles static calls to custom methods for the class.
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() statically. The called method has no access to the internal array because no object is available.
Examples:
Map::method( 'foo', function( $arg1, $arg2 ) {} ); Map::foo( $arg1, $arg2 );
Returns the elements after the given one.
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:
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']
Returns the elements as a plain array.
public function all() : array
@return array Plain array
Examples:
Map::from( ['a'] )->all();// ['a']
Sorts all elements in reverse order and maintains the key association.
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:
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'
Sorts a copy of all elements in reverse order and maintains the key association.
public function arsorted( 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 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:
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'
Sorts all elements and maintains the key association.
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:
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'] )->arsort( SORT_STRING|SORT_FLAG_CASE );// [1 => 'b', 0 => 'C'] because 'C' -> 'c' and 'c' > 'b'
Sorts a copy of all elements and maintains the key association.
public function asorted( 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 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:
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'
Returns the value at the given position.
public function at( int $pos )
@param int $pos
Position of the value in the map
@return mixed�null 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:
Map::from( [1, 3, 5] )->at( 0 );// 1Map::from( [1, 3, 5] )->at( 1 );// 3Map::from( [1, 3, 5] )->at( -1 );// 5Map::from( [1, 3, 5] )->at( 3 );// NULL
Returns the average of all integer and float values in the map.
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
NULL values are treated as 0, non-numeric values will generate an error.
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:
Map::from( [1, 3, 5] )->avg();// 3Map::from( [1, null, 5] )->avg();// 3Map::from( [1, 'sum', 5] )->avg();// 2Map::from( [['p' => 30], ['p' => 50], ['p' => 10]] )->avg( 'p' );// 30Map::from( [['i' => ['p' => 30]], ['<sp