Iterating

each

Definition

1
Arr::each(array|Iterator|IteratorAggregate $iterable, callable $callback, int $mode = self::EACH_VALUE): array|Iterator|IteratorAggregate
Copied!

Description

Traverse through array or iterable object and call callback for each element (ignoring the result).

Modes

Constant name
Description
EACH_VALUE
Iterate using callback in form of function($value)
EACH_KEY_VALUE
Iterate using callback in form of function($key, $value)
EACH_VALUE_KEY
Iterate using callback in form of function($value, $key)
EACH_VALUE_KEYS_LIST
Iterate using callback in form of function($value, $key1, $key2, ...)
Only for array $iterable
EACH_KEYS_ARRAY_VALUE
Iterate using callback in form of function(array $keys, $value)
Only for array $iterable

Examples

1
$array = [
2
1 => [
3
2 => 'a',
4
3 => 'b',
5
4 => [
6
5 => 'c',
7
],
8
],
9
'test' => 'd',
10
];
11
12
// Value only - using default EACH_VALUE mode
13
Arr::each($array, function ($value) {
14
print_r($value);
15
// [ 2 => 'a', ...]
16
// 'd'
17
});
18
19
// Key, Value
20
Arr::each($array, function ($key, $value) {
21
echo "{$key}: \t\t";
22
print_r($value);
23
// 1: [2 => 'a', ...]
24
// test: 'd'
25
}, Arr::EACH_KEY_VALUE);
26
27
// Value, Key
28
Arr::each($array, function ($value, $key) {
29
echo "{$key}: \t\t";
30
print_r($value);
31
// 1: [2 => 'a', ...]
32
// test: 'd'
33
}, Arr::EACH_VALUE_KEY);
34
35
// Value, Keys list
36
Arr::each($array, function ($value, ...$keys) {
37
echo implode('.', $keys) . ': \t\t';
38
print_r($value);
39
// 1.2: 'a'
40
// 1.3: 'b'
41
// 1.4.5: 'c'
42
// test: 'd'
43
}, Arr::EACH_VALUE_KEYS_LIST);
44
45
46
// Keys array, value
47
Arr::each($array, function (array $keys, $value) {
48
echo implode('.', $keys) . ': \t\t';
49
print_r($value);
50
// 1.2: 'a'
51
// 1.3: 'b'
52
// 1.4.5: 'c'
53
// test: 'd'
54
}, Arr::EACH_KEYS_ARRAY_VALUE);
Copied!
Last modified 1yr ago
Copy link