-
Notifications
You must be signed in to change notification settings - Fork 33
/
get.php
41 lines (37 loc) · 1.11 KB
/
get.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
<?php
namespace collections;
/**
* get item of an array by index , aceepting nested index
*
** __::get(['foo' => ['bar' => 'ter']], 'foo.bar');
** // → 'ter'
*
* @param array|object $collection array of values
* @param string $key array key or object attribute
* @param \Closure|mixed $default default value to return if index not exist
*
* @return array|mixed|null
*
*/
function get($collection, $key, $default = null)
{
if (isset($collection[$key])) {
return $collection[$key];
}
foreach (\explode('.', $key) as $segment) {
if (\is_object($collection)) {
if (isset($collection->{$segment})) {
$collection = $collection->{$segment};
} else {
return $default && $default instanceof \Closure ? $default() : $default;
}
} else {
if (isset($collection[$segment])) {
$collection = $collection[$segment];
} else {
return $default && $default instanceof \Closure ? $default() : $default;
}
}
}
return $collection;
}