Mapping

map

Definition

1
Arr::map(array $array, callable $callback, int $mode = Arr::MAP_ARRAY_KEY_VALUE): array
Copied!

Description

Applies a callback to the elements of given array. Arguments supplied to callback differs depending on selected $mode.
For backward compatibility using map(callable, array) is still possible but is deprecated and will issue appropriate warning

Modes

Constant name
Description
MAP_ARRAY_KEY_VALUE
Map array using callback in form of function($key, $value)
MAP_ARRAY_VALUE_KEYS_LIST
Map array using callback in form of function($value, $key1, $key2, ...)
MAP_ARRAY_KEYS_ARRAY_VALUE
Map array using callback in form of function(array $keys, $value)
MAP_ARRAY_VALUE_KEY
Map array using callback in form of function($value, $key)

Examples

1
$array1 = ['a', 'b', 'c'];
2
$array2 = [
3
1 => [
4
2 => 'a',
5
3 => 'b',
6
4 => [
7
5 => 'c',
8
],
9
],
10
'test' => 'd',
11
];
12
13
$mapKeyValue = function ($key, $value) {
14
return "{$key} -> {$value}";
15
};
16
// Mind that $value is a first argument here
17
$mapValueKey = function ($value, $key) {
18
return "{$key} -> {$value}";
19
};
20
$mapKeysValue = function ($keys, $value) {
21
return implode('.', $keys) . " -> {$value}";
22
};
23
$mapValueKeysList = function ($value, $key1, $key2) {
24
return "$key1.$key2 -> {$value}";
25
};
26
27
// Equivalent to using MAP_ARRAY_KEY_VALUE as mode (3rd) argument
28
Arr::map($array1, $mapKeyValue) -> ['0 -> a', '1 -> b', '2 -> c']
29
30
// Resemble array_map function but with array supplied as first argument
31
Arr::map($array1, $mapValueKey) -> ['0 -> a', '1 -> b', '2 -> c']
32
33
// Map multidimensional array using keys array
34
Arr::map($array2, $mapKeysValue, Arr::MAP_ARRAY_KEYS_ARRAY_VALUE) ->
35
[
36
1 => [
37
2 => '1.2 -> a',
38
3 => '1.3 -> b',
39
4 => [
40
5 => '1.4.5 -> c',
41
],
42
],
43
'test' => 'test -> d',
44
]
45
46
// Map multidimensional array using keys list (mind that all keys above 2nd are ignored due to callback function syntax)
47
Arr::map($array2, $mapValueKeysList, Arr::MAP_ARRAY_VALUE_KEYS_LIST) ->
48
[
49
1 => [
50
2 => '1.2 -> a',
51
3 => '1.3 -> b',
52
4 => [
53
5 => '1.4 -> c',
54
],
55
],
56
'test' => 'test -> d',
57
]
Copied!

mapObjects

Definition

1
Arr::mapObjects(array $objects, string $method, ...$args): array
Copied!

Description

Map array of object to values returned from objects method

Examples

1
$object = new class() {
2
function test($arg = 0) {
3
return 1 + $arg;
4
}
5
};
6
$array = [$object, $object, $object];
7
8
Arr::mapObjects($array, 'test') -> [1, 1, 1]
9
Arr::mapObjects($array, 'test', 2) -> [3, 3, 3]
Copied!
Last modified 2yr ago
Copy link