forked from maciejczyzewski/bottomline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoForEachRight.php
59 lines (56 loc) · 1.42 KB
/
doForEachRight.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
namespace collections;
/**
* Iterate an array or other foreach-able without making a copy of it.
*
* Code for PHP_VERSION >= 5.5.(using `yield`) is from mpen and linepogl
* See https://stackoverflow.com/a/36605605/1956471
*
* @param array|\Traversable $iterable
* @return \Generator
*/
if (version_compare(PHP_VERSION, '5.5.0', '<')) {
eval('
function iter_reverse($iterable) {
return array_reverse($iterable, true);
}
');
} else {
eval('
function iter_reverse($iterable) {
for (end($iterable); ($key = key($iterable)) !== null; prev($iterable)) {
yield $key => current($iterable);
}
}
');
}
/**
* Iterate over elements of the collection, from right to left, and invokes iteratee
* for each element.
*
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning false.
*
* **Usage**
*
* ```php
* __::doForEachRight([1, 2, 3], function ($value, $key, $collection) {
* print_r($value);
* });
* ```
*
* **Result**
*
* ```
* (Side effect: print 3, 2, 1)
* ```
*
* @param array|object $collection The collection to iterate over.
* @param \Closure $iteratee The function to call for each value.
*
* @return void
*/
function doForEachRight($collection, \Closure $iteratee)
{
\__::doForEach(iter_reverse($collection), $iteratee);
}