array_merge_recursive_distinct()   B
last analyzed

Complexity

Conditions 10
Paths 8

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 15
nc 8
nop 1
dl 0
loc 26
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Jenky\Hermes;
4
5
/**
6
 * Merges any number of arrays / parameters recursively, using the left array as base, giving priority to the right array. Replacing entries with string keys with values from latter arrays.
7
 *
8
 * @param  array[] $arrays
9
 * @return array
10
 */
11
function array_merge_recursive_distinct(...$arrays)
12
{
13
    if (count($arrays) < 2) {
14
        return empty($arrays) ? [] : $arrays[0];
15
    }
16
17
    $merged = array_shift($arrays);
18
19
    foreach ($arrays as $array) {
20
        foreach ($array as $key => $value) {
21
            if (is_array($value) && (isset($merged[$key]) && is_array($merged[$key]))) {
22
                $merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
23
            } else {
24
                if (is_numeric($key)) {
25
                    if (! in_array($value, $merged)) {
26
                        $merged[] = $value;
27
                    }
28
                } else {
29
                    $merged[$key] = $value;
30
                }
31
            }
32
        }
33
        unset($key, $value);
34
    }
35
36
    return $merged;
37
}
38