-
Notifications
You must be signed in to change notification settings - Fork 0
/
Arr.php
114 lines (104 loc) · 3.19 KB
/
Arr.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
namespace CleantalkSP\Common\Helpers;
/**
* Class Arr
* Gather static functions designed to ease work with arrays
*
* @version 1.0.0
* @package CleantalkSP\Common\Helpers
* @author Cleantalk team (welcome@cleantalk.org)
* @copyright (C) 2014 CleanTalk team (http://cleantalk.org)
* @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html
* @see https://github.com/CleanTalk/security-malware-firewall
*/
class Arr
{
/**
* @param array $arr
*
* @return bool
* @psalm-suppress PossiblyUnusedMethod
*/
public static function reindex(&$arr)
{
if (! count($arr)) {
return false;
}
for ($reindex_key = 0, $key = 0, $max_key = max(array_keys($arr)); $key <= $max_key; $key++) {
if (isset($arr[$key])) {
if ($reindex_key === $key) {
$reindex_key++;
continue;
}
$arr[$reindex_key++] = $arr[$key];
unset($arr[$key]);
}
}
return true;
}
/**
* Merging arrays without reseting numeric keys
*
* @param array $arr1 One-dimentional array
* @param array $arr2 One-dimentional array
*
* @return array Merged array
* @psalm-suppress PossiblyUnusedMethod
*/
public static function mergeWithSavingNumericKeys($arr1, $arr2)
{
foreach ($arr2 as $key => $val) {
$arr1[$key] = $val;
}
return $arr1;
}
/**
* Merging arrays without reseting numeric keys recursive
*
* @param array $arr1 One-dimentional array
* @param array $arr2 One-dimentional array
*
* @return array Merged array
*/
public static function mergeWithSavingNumericKeysRecursive($arr1, $arr2)
{
foreach ($arr2 as $key => $val) {
// Array | array => array
if (isset($arr1[$key]) && is_array($arr1[$key]) && is_array($val)) {
$arr1[$key] = self::mergeWithSavingNumericKeysRecursive($arr1[$key], $val);
// Scalar | array => array
} elseif (isset($arr1[$key]) && ! is_array($arr1[$key]) && is_array($val)) {
$tmp = $arr1[$key];
$arr1[$key] = $val;
$arr1[$key][] = $tmp;
// array | scalar => array
} elseif (isset($arr1[$key]) && is_array($arr1[$key]) && ! is_array($val)) {
$arr1[$key][] = $val;
// scalar | scalar => scalar
} else {
$arr1[$key] = $val;
}
}
return $arr1;
}
/**
* Modifies the array $array. Paste $insert on $position
*
* @param array $array
* @param int|string $position
* @param mixed $insert
*/
public static function insert(&$array, $position, $insert)
{
if (is_int($position)) {
array_splice($array, $position, 0, $insert);
} else {
$pos = array_search($position, array_keys($array));
$array = array_merge(
array_slice($array, 0, $pos),
$insert,
array_slice($array, $pos)
);
}
}
}