Completed
Branch master (f8a0b6)
by Arnold
06:06
created

array_functions.php ➔ array_only()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 3
c 1
b 0
f 1
nc 1
nop 2
dl 0
loc 5
ccs 2
cts 2
cp 1
crap 1
rs 9.4285
1
<?php
2
3
namespace Jasny;
4
5
/**
6
 * Get items from an array.
7
 * Set default values using [key => value].
8
 *
9
 * <code>
10
 *   list($foo, $bar, $useAll) = extract_keys($_GET, ['foo', 'bar', 'all' => false]);
11
 * </cody>
12
 *
13
 * @param array $array
14
 * @param array $keys
15
 * @return array
16
 */
17
function extract_keys(array $array, array $keys)
18
{
19 1
    $values = [];
20
21 1
    foreach ($keys as $i => $v) {
22 1
        $key = is_int($i) ? $v : $i;
23 1
        $default = is_int($i) ? null : $v;
24
        
25 1
        $values[] = isset($array[$key]) ? $array[$key] : $default;
26 1
    }
27
28 1
    return $values;
29
}
30
31
/**
32
 * Walk through the array and unset an item with the key
33
 *
34
 * @param array        $array  Array with objects or arrays
35
 * @param string|array $key
36
 */
37
function array_unset(array &$array, $key)
38
{
39 2
    foreach ($array as &$item) {
40 2
        if (is_object($item)) {
41 1
            foreach ((array)$key as $k) {
42 1
                if (isset($item->$k)) unset($item->$k);
43 1
            }
44 2
        } elseif (is_array($item)) {
45 1
            foreach ((array)$key as $k) {
46 1
                if (isset($item[$k])) unset($item[$k]);
47 1
            }
48 1
        }
49 2
    }
50 2
}
51
52
/**
53
 * Return an array with only the specified keys.
54
 *
55
 * @param array $array
56
 * @param array $keys
57
 * @return array
58
 */
59
function array_only(array $array, array $keys)
60
{
61 1
    $intersect = array_fill_keys($keys, null);
62 1
    return array_intersect_key($array, $intersect);
63
}
64
65
/**
66
 * Return an array without the specified keys.
67
 *
68
 * @param array $array
69
 * @param array $keys
70
 * @return array
71
 */
72
function array_without(array $array, array $keys)
73
{
74 1
    $intersect = array_fill_keys($keys, null);
75 1
    return array_diff_key($array, $intersect);
76
}
77