-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterable.php
63 lines (48 loc) · 1.06 KB
/
iterable.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
60
61
62
63
<?php
declare(strict_types=1);
// https://wiki.php.net/rfc/iterable
function returnNumericArray(iterable $array) : iterable {
foreach ($array as $element) {
$elements[] = $element;
}
return $elements ?? [];
}
$array = ['one' => 1, 'two' => 2];
// array example
print_r(returnNumericArray($array));
// object example
class AssociativeArrayIterator implements Iterator {
protected $array;
public function __construct(array $array) {
$this->array = $array;
}
public function current() {
return current($this->array);
}
public function key() : ?string {
return key($this->array);
}
public function next() : void {
next($this->array);
}
public function rewind() : void {
reset($this->array);
}
public function valid() : bool {
return isset($this->array[$this->key()]);
}
}
print_r(returnNumericArray(new AssociativeArrayIterator($array)));
/*
Output
Array
(
[0] => 1
[1] => 2
)
Array
(
[0] => 1
[1] => 2
)
*/