-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayHelper.php
1240 lines (1090 loc) · 39.9 KB
/
ArrayHelper.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Qubus\Support
*
* @link https://github.com/QubusPHP/support
* @copyright 2022
* @author Joshua Parker <joshua@joshuaparker.dev>
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types=1);
namespace Qubus\Support;
use ArrayAccess;
use BadMethodCallException;
use Closure;
use Iterator;
use Qubus\Exception\Data\TypeException;
use function abs;
use function array_combine;
use function array_filter;
use function array_key_exists;
use function array_keys;
use function array_map;
use function array_merge;
use function array_pop;
use function array_search;
use function array_shift;
use function array_slice;
use function array_splice;
use function array_sum;
use function array_values;
use function arsort;
use function asort;
use function count;
use function explode;
use function func_get_arg;
use function func_get_args;
use function implode;
use function in_array;
use function is_array;
use function is_int;
use function is_numeric;
use function is_object;
use function is_string;
use function preg_match;
use function preg_replace;
use function property_exists;
use function Qubus\Support\Helpers\call_qubus_func_array;
use function stripos;
use const SORT_REGULAR;
class ArrayHelper
{
/**
* Gets a dot-notated key from an array, with a default value if it does
* not exist.
*
* @param array|ArrayAccess $array $array The search array.
* @param mixed|null $key The dot-notated key or array of keys.
* @param string|null $default The default value
* @return mixed
* @throws TypeException
*/
public function get(array|ArrayAccess $array, mixed $key = null, ?string $default = null): mixed
{
if (! is_array($array) && ! $array instanceof ArrayAccess) {
throw new TypeException('First parameter must be an array or ArrayAccess object.');
}
if ($key === null) {
return $array;
}
if (is_array($key)) {
$return = [];
foreach ($key as $k) {
$return[$k] = $this->get($array, $k, $default);
}
return $return;
}
if (is_object($key)) {
$key = (string) $key;
}
if (is_object($array)) {
if (property_exists($array, $key)) {
return $array->$key;
}
} elseif (array_key_exists($key, $array)) {
return $array[$key];
}
foreach (explode('.', $key) as $keyPart) {
if (($array instanceof ArrayAccess && isset($array[$keyPart])) === false) {
if (! is_array($array) || ! array_key_exists($keyPart, $array)) {
return $this->value($default);
}
}
$array = $array[$keyPart];
}
return $array;
}
/**
* Set an array item (dot-notated) to the value.
*
* @param array $array The array to insert it into
* @param mixed $key The dot-notated key to set or array of keys
* @param mixed|null $value The value
* @return void
*/
public function set(array &$array, mixed $key, mixed $value = null): void
{
if ($key === null) {
$array = $value;
return;
}
if (is_array($key)) {
foreach ($key as $k => $v) {
$this->set($array, $k, $v);
}
} else {
$keys = explode('.', $key);
while (count($keys) > 1) {
$key = array_shift($keys);
if (! isset($array[$key]) || ! is_array($array[$key])) {
$array[$key] = [];
}
$array = &$array[$key];
}
$array[array_shift($keys)] = $value;
}
}
/**
* Pluck an array of values from an array.
*
* @param array $array Collection of arrays to pluck from.
* @param string $key Key of the value to pluck.
* @param bool|int|string|null $index Optional return array index key, true for original index.
* @return array Array of plucked values.
* @throws TypeException
*/
public function pluck(array $array, string $key, bool|int|string $index = null): array
{
$return = [];
$getDeep = str_contains($key, '.') !== false;
if (! $index) {
foreach ($array as $i => $a) {
$return[] = is_object($a) &&
! $a instanceof ArrayAccess ? $a->{$key} : ($getDeep ? $this->get($a, $key) : $a[$key]);
}
} else {
foreach ($array as $i => $a) {
$index !== true && $i = is_object($a) && ! $a instanceof ArrayAccess ? $a->{$index} : $a[$index];
$return[$i] = is_object($a) &&
! $a instanceof ArrayAccess ? $a->{$key} : ($getDeep ? $this->get($a, $key) : $a[$key]);
}
}
return $return;
}
/**
* Array_key_exists with a dot-notated key from an array.
*
* @param array|ArrayAccess $array $array The search array
* @param mixed $key The dot-notated key or array of keys
* @return bool
* @throws TypeException
*/
public function keyExists(array|ArrayAccess $array, mixed $key): bool
{
if (! is_array($array) && ! $array instanceof ArrayAccess) {
throw new TypeException('First parameter must be an array or ArrayAccess object.');
}
is_object($key) && $key = (string) $key;
if (! is_string($key)) {
return false;
}
if (array_key_exists($key, $array)) {
return true;
}
foreach (explode('.', $key) as $keyPart) {
if (($array instanceof ArrayAccess && isset($array[$keyPart])) === false) {
if (! is_array($array) || ! array_key_exists($keyPart, $array)) {
return false;
}
}
$array = $array[$keyPart];
}
return true;
}
/**
* Unsets dot-notated k?string ey from an array
*
* @param array $array The search array
* @param mixed|null $key The dot-notated key or array of keys
* @return mixed
*/
public function delete(array &$array, mixed $key = null): mixed
{
if ($key === null) {
return false;
}
if (is_array($key)) {
$return = [];
foreach ($key as $k) {
$return[$k] = $this->delete($array, $k);
}
return $return;
}
$keyParts = explode('.', $key);
if (! array_key_exists($keyParts[0], $array)) {
return false;
}
$thisKey = array_shift($keyParts);
if (! empty($keyParts)) {
$key = implode('.', $keyParts);
return $this->delete($array[$thisKey], $key);
} else {
unset($array[$thisKey]);
}
return true;
}
/**
* Converts a multidimensional associative array into an array of key => values with the provided field names.
*
* @param array|Iterator $assoc The array to convert.
* @param string $keyField The field name of the key field.
* @param string $valField The field name of the value field.
* @return array
* @throws TypeException
*/
public function assocToKeyVal(array|Iterator $assoc, string $keyField, string $valField): array
{
if (! is_array($assoc) && ! $assoc instanceof Iterator) {
throw new TypeException('The first parameter must be an array.');
}
$output = [];
foreach ($assoc as $row) {
if (isset($row[$keyField]) && isset($row[$valField])) {
$output[$row[$keyField]] = $row[$valField];
}
}
return $output;
}
/**
* Converts an array of key => values into a multidimensional associative array with the provided field names
*
* @param array|Iterator $array $array the array to convert
* @param string $keyField the field name of the key field
* @param string $valField the field name of the value field
* @return array
* @throws TypeException
*/
public function keyValToAssoc(array|Iterator $array, string $keyField, string $valField): array
{
if (! is_array($array) && ! $array instanceof Iterator) {
throw new TypeException('The first parameter must be an array.');
}
$output = [];
foreach ($array as $key => $value) {
$output[] = [
$keyField => $key,
$valField => $value,
];
}
return $output;
}
/**
* Converts the given 1 dimensional non-associative array to an associative
* array.
*
* The array given must have an even number of elements or null will be returned.
*
* $this->toAssoc(['foo','bar']);
*
* @param array $arr the array to change
* @return array|null the new array or null
* @throws BadMethodCallException
*/
public function toAssoc(array $arr): ?array
{
if (($count = count($arr)) % 2 > 0) {
throw new BadMethodCallException('Number of values in toAssoc must be even.');
}
$keys = $vals = [];
for ($i = 0; $i < $count - 1; $i += 2) {
$keys[] = array_shift($arr);
$vals[] = array_shift($arr);
}
return array_combine($keys, $vals);
}
/**
* Checks if the given array is an assoc array.
*
* @param array $arr the array to check
* @return bool True if it's an assoc array, false if not.
*/
public function isAssoc(array $arr): bool
{
$counter = 0;
foreach ($arr as $key => $unused) {
if (! is_int($key) || $key !== $counter++) {
return true;
}
}
return false;
}
/**
* Flattens a multi-dimensional associative array down into a 1 dimensional
* associative array.
*
* @param array $array the array to flatten
* @param string $glue what to glue the keys together with
* @param bool $reset whether to reset and start over on a new array
* @param bool $indexed whether to flatten only associative array's, or also indexed ones
* @return array
*/
public function flatten(array $array, string $glue = ':', bool $reset = true, bool $indexed = true): array
{
static $return = [];
static $currKey = [];
if ($reset) {
$return = [];
$currKey = [];
}
foreach ($array as $key => $val) {
$currKey[] = $key;
if (is_array($val) && ($indexed || array_values($val) !== $val)) {
$this->flatten($val, $glue, false, $indexed);
} else {
$return[implode($glue, $currKey)] = $val;
}
array_pop($currKey);
}
return $return;
}
/**
* Flattens a multi-dimensional associative array down into a 1 dimensional
* associative array.
*
* @param array $array the array to flatten
* @param string $glue what to glue the keys together with
* @param bool $reset whether to reset and start over on a new array
* @return array
*/
public function flattenAssoc(array $array, string $glue = ':', bool $reset = true): array
{
return $this->flatten($array, $glue, $reset, false);
}
/**
* Reverse a flattened array in its original form.
*
* @param array $array flattened array
* @param string $glue glue used in flattening
* @return array The unflattened array.
*/
public function reverseFlatten(array $array, string $glue = ':'): array
{
$return = [];
foreach ($array as $key => $value) {
if (stripos($key, $glue) !== false) {
$keys = explode($glue, $key);
$temp = &$return;
while (count($keys) > 1) {
$key = array_shift($keys);
$key = is_numeric($key) ? (int) $key : $key;
if (! isset($temp[$key]) || ! is_array($temp[$key])) {
$temp[$key] = [];
}
$temp = &$temp[$key];
}
$key = array_shift($keys);
$key = is_numeric($key) ? (int) $key : $key;
$temp[$key] = $value;
} else {
$key = is_numeric($key) ? (int) $key : $key;
$return[$key] = $value;
}
}
return $return;
}
/**
* Filters an array on prefixed associative keys.
*
* @param array $array The array to filter.
* @param string $prefix Prefix to filter on.
* @param bool $removePrefix Whether to remove the prefix.
* @return array
*/
public function filterPrefixed(array $array, string $prefix, bool $removePrefix = true): array
{
$return = [];
foreach ($array as $key => $val) {
if (preg_match('/^' . $prefix . '/', $key)) {
if ($removePrefix === true) {
$key = preg_replace('/^' . $prefix . '/', '', $key);
}
$return[$key] = $val;
}
}
return $return;
}
/**
* Recursive version of PHP's array_filter().
*
* @param array $array The array to filter.
* @param callable|null $callback $callback The callback that determines whether a value is filtered.
* @return array
*/
public function filterRecursive(array $array, ?callable $callback = null): array
{
foreach ($array as &$value) {
if (is_array($value)) {
$value = $callback === null
? $this->filterRecursive($value)
: $this->filterRecursive($value, $callback);
}
}
return $callback === null ? array_filter($array) : array_filter($array, $callback);
}
/**
* Removes items from an array that match a key prefix.
*
* @param array $array The array to remove from.
* @param string $prefix Prefix to filter on.
* @return array
*/
public function removePrefixed(array $array, string $prefix): array
{
foreach ($array as $key => $val) {
if (preg_match('/^' . $prefix . '/', $key)) {
unset($array[$key]);
}
}
return $array;
}
/**
* Filters an array on suffixed associative keys.
*
* @param array $array The array to filter.
* @param string $suffix Suffix to filter on.
* @param bool $removeSuffix Whether to remove the suffix.
* @return array
*/
public function filterSuffixed(array $array, string $suffix, bool $removeSuffix = true): array
{
$return = [];
foreach ($array as $key => $val) {
if (preg_match('/' . $suffix . '$/', $key)) {
if ($removeSuffix === true) {
$key = preg_replace('/' . $suffix . '$/', '', $key);
}
$return[$key] = $val;
}
}
return $return;
}
/**
* Removes items from an array that match a key suffix.
*
* @param array $array The array to remove from.
* @param string $suffix Suffix to filter on.
* @return array
*/
public function removeSuffixed(array $array, string $suffix): array
{
foreach ($array as $key => $val) {
if (preg_match('/' . $suffix . '$/', $key)) {
unset($array[$key]);
}
}
return $array;
}
/**
* Filters an array by an array of keys
*
* @param array $array The array to filter.
* @param array $keys The keys to filter
* @param bool $remove If true, removes the matched elements.
* @return array
*/
public function filterKeys(array $array, array $keys, bool $remove = false): array
{
$return = [];
foreach ($keys as $key) {
if (array_key_exists($key, $array)) {
$remove || $return[$key] = $array[$key];
if ($remove) {
unset($array[$key]);
}
}
}
return $remove ? $array : $return;
}
/**
* Insert value(s) into an array, mostly an array_splice alias.
*
* WARNING: original array is edited by reference, only bool success is returned.
*
* @param array $original The original array (by reference).
* @param mixed $value The value(s) to insert, if you want to insert an array
* it needs to be in an array itself.
* @param int $pos The numeric position at which to insert, negative to count from the end backwards.
* @return bool False when array shorter than $pos, otherwise true
*/
public function insert(array &$original, mixed $value, int $pos): bool
{
if (count($original) < abs($pos)) {
return false;
}
array_splice($original, $pos, 0, $value);
return true;
}
/**
* Insert value(s) into an array, mostly an array_splice alias
* WARNING: original array is edited by reference, only bool success is returned
*
* @param array $original The original array (by reference)
* @param mixed $values The value(s) to insert, if you want to insert an array
* it needs to be in an array itself.
* @param int $pos The numeric position at which to insert, negative to count from the end backwards.
* @return bool false when array shorter than $pos, otherwise true
*/
public function insertAssoc(array &$original, mixed $values, int $pos): bool
{
if (count($original) < abs($pos)) {
return false;
}
$original = array_slice($original, 0, $pos, true) + $values + array_slice($original, $pos, null, true);
return true;
}
/**
* Insert value(s) into an array before a specific key.
*
* WARNING: original array is edited by reference, only bool success is returned.
*
* @param array $original The original array (by reference).
* @param mixed $value The value(s) to insert, if you want to insert an array
* it needs to be in an array itself.
* @param int|string $key The key before which to insert.
* @param bool $isAssoc Whether the input is an associative array.
* @return bool False when key isn't found in the array, otherwise true.
*/
public function insertBeforeKey(array &$original, mixed $value, int|string $key, bool $isAssoc = false): bool
{
$pos = array_search($key, array_keys($original));
if ($pos === false) {
return false;
}
return $isAssoc ? $this->insertAssoc($original, $value, $pos) : $this->insert($original, $value, $pos);
}
/**
* Insert value(s) into an array after a specific key.
*
* WARNING: original array is edited by reference, only bool success is returned.
*
* @param array $original The original array (by reference).
* @param mixed $value The value(s) to insert, if you want to insert an array
* it needs to be in an array itself.
* @param int|string $key The key after which to insert.
* @param bool $isAssoc Whether the input is an associative array.
* @return bool False when key isn't found in the array, otherwise true.
*/
public function insertAfterKey(array &$original, mixed $value, int|string $key, bool $isAssoc = false): bool
{
$pos = array_search($key, array_keys($original));
if ($pos === false) {
return false;
}
return $isAssoc ? $this->insertAssoc($original, $value, $pos + 1) : $this->insert($original, $value, $pos + 1);
}
/**
* Insert value(s) into an array after a specific value (first found in array).
*
* @param array $original The original array (by reference).
* @param mixed $value The value(s) to insert, if you want to insert an array
* it needs to be in an array itself.
* @param int|string $search The value after which to insert.
* @param bool $isAssoc Whether the input is an associative array.
* @return bool False when value isn't found in the array, otherwise true.
*/
public function insertAfterValue(array &$original, mixed $value, int|string $search, bool $isAssoc = false): bool
{
$key = array_search($search, $original);
if ($key === false) {
return false;
}
return $this->insertAfterKey($original, $value, $key, $isAssoc);
}
/**
* Insert value(s) into an array before a specific value (first found in array)
*
* @param array $original The original array (by reference).
* @param mixed $value The value(s) to insert, if you want to insert an array.
* it needs to be in an array itself.
* @param int|string $search The value after which to insert.
* @param bool $isAssoc Whether the input is an associative array.
* @return bool False when value isn't found in the array, otherwise true.
*/
public function insertBeforeValue(array &$original, mixed $value, int|string $search, bool $isAssoc = false): bool
{
$key = array_search($search, $original);
if ($key === false) {
return false;
}
return $this->insertBeforeKey($original, $value, $key, $isAssoc);
}
/**
* Sorts a multi-dimensional array by it's values.
*
* @param array $array The array to fetch from.
* @param string $key The key to sort by.
* @param string $order The order (asc or desc).
* @param int $sortFlags The php sort type flag.
* @return array
* @throws TypeException
*/
public function sort(
array $array,
string $key,
string $order = 'asc',
int $sortFlags = SORT_REGULAR
): array {
if (empty($array)) {
return $array;
}
$b = [];
foreach ($array as $k => $v) {
$b[$k] = $this->get($v, $key);
}
switch ($order) {
case 'asc':
asort($b, $sortFlags);
break;
case 'desc':
arsort($b, $sortFlags);
break;
default:
throw new TypeException('$this->sort() - $order must be asc or desc.');
break;
}
$c = [];
foreach ($b as $key => $val) {
$c[] = $array[$key];
}
return $c;
}
/**
* Sorts an array on multiple values, with deep sorting support.
*
* @param array $array Collection of arrays/objects to sort.
* @param array $conditions Sorting conditions.
* @param bool $ignoreCase Whether to sort case-insensitive.
* @return array
* @throws TypeException
*/
public function multisort(array $array, array $conditions, bool $ignoreCase = false): array
{
$temp = [];
$keys = array_keys($conditions);
foreach ($keys as $key) {
$temp[$key] = $this->pluck($array, $key, true);
is_array($conditions[$key]) || $conditions[$key] = [$conditions[$key]];
}
$args = [];
foreach ($keys as $key) {
$args[] = $ignoreCase ? array_map('strtolower', $temp[$key]) : $temp[$key];
foreach ($conditions[$key] as $flag) {
$args[] = $flag;
}
}
$args[] = &$array;
call_qubus_func_array('array_multisort', $args);
return $array;
}
/**
* Find the average of an array.
*
* @param array $array The array containing the values.
* @return float|int The average value.
*/
public function average(array $array): float|int
{
// No arguments passed, lets not divide by 0
if (! ($count = count($array)) > 0) {
return 0;
}
return array_sum($array) / $count;
}
/**
* Replaces key names in an array by names in the $replace parameter.
*
* @param array $source The array containing the key/value combinations
* @param array|string $replace Key to replace or array containing the replacement keys
* @param string|null $newKey The replacement key
* @return array The array with the new keys.
*/
public function replaceKey(array $source, array|string $replace, ?string $newKey = null): array
{
if (is_string($replace)) {
$replace = [$replace => $newKey];
}
$result = [];
foreach ($source as $key => $value) {
if (array_key_exists($key, $replace)) {
$result[$replace[$key]] = $value;
} else {
$result[$key] = $value;
}
}
return $result;
}
/**
* Merge 2 arrays recursively, differs in 2 important ways from array_merge_recursive().
*
* When there's 2 different values and not both arrays, the latter value overwrites the earlier
* instead of merging both into an array.
*
* Numeric keys that don't conflict aren't changed, only when a numeric key already exists is the
* value added using array_push().
*
* @return array
* @throws TypeException
*/
public function merge(): array
{
$array = func_get_arg(0);
$arrays = array_slice(func_get_args(), 1);
if (! is_array($array)) {
throw new TypeException('$this->merge() - all arguments must be arrays.');
}
foreach ($arrays as $arr) {
if (! is_array($arr)) {
throw new TypeException('$this->merge() - all arguments must be arrays.');
}
foreach ($arr as $k => $v) {
// numeric keys are appended
if (is_int($k)) {
array_key_exists($k, $array) ? $array[] = $v : $array[$k] = $v;
} elseif (is_array($v) && array_key_exists($k, $array) && is_array($array[$k])) {
$array[$k] = $this->merge($array[$k], $v);
} else {
$array[$k] = $v;
}
}
}
return $array;
}
/**
* Merge 2 arrays recursively, differs in 2 important ways from array_merge_recursive().
*
* When there's 2 different values and not both arrays, the latter value overwrites the earlier
* instead of merging both into an array. Numeric keys are never changed.
*
* @return array
* @throws TypeException
*/
public function mergeAssoc(): array
{
$array = func_get_arg(0);
$arrays = array_slice(func_get_args(), 1);
if (! is_array($array)) {
throw new TypeException('$this->mergeAssoc() - all arguments must be arrays.');
}
foreach ($arrays as $arr) {
if (! is_array($arr)) {
throw new TypeException('$this->mergeAssoc() - all arguments must be arrays.');
}
foreach ($arr as $k => $v) {
if (is_array($v) && array_key_exists($k, $array) && is_array($array[$k])) {
$array[$k] = $this->mergeAssoc($array[$k], $v);
} else {
$array[$k] = $v;
}
}
}
return $array;
}
/**
* Prepends a value with an associative key to an array.
*
* Will overwrite if the value exists.
*
* @param array $arr The array to prepend to
* @param array|string $key The key or array of keys and values
* @param mixed|null $value The value to prepend
*/
public function prepend(array &$arr, array|string $key, mixed $value = null): string|array
{
$arr = (is_array($key) ? $key : [$key => $value]) + $arr;
return $arr;
}
/**
* Recursive in_array
*
* @param mixed $needle What to search for.
* @param array $haystack Array to search in.
* @return bool Whether the needle is found in the haystack.
*/
public function inArrayRecursive(mixed $needle, array $haystack, bool $strict = false): bool
{
foreach ($haystack as $value) {
if (! $strict && $needle === $value) {
return true;
} elseif ($needle === $value) {
return true;
} elseif (is_array($value) && $this->inArrayRecursive($needle, $value, $strict)) {
return true;
}
}
return false;
}
/**
* Checks if the given array is a multidimensional array.
*
* @param array $arr The array to check
* @param bool $allKeys If true, check that all elements are arrays.
* @return bool True if its a multidimensional array, false if not.
*/
public function isMulti(array $arr, bool $allKeys = false): bool
{
$values = array_filter($arr, 'is_array');
return $allKeys ? count($arr) === count($values) : count($values) > 0;
}
/**
* Searches the array for a given value and returns the
* corresponding key or default value.
*
* If $recursive is set to true, then the $this->search()
* method will return a delimiter-notated key using the
* $delimiter parameter.
*
* @param array|ArrayAccess $array $array The search array.
* @param mixed $value The searched value.
* @param string|null $default The default value.
* @param bool $recursive Whether to get keys recursive.
* @param string $delimiter The delimiter, when $recursive is true.
* @param bool $strict If true, do a strict key comparison.
* @return string|bool|null
* @throws TypeException
*/
public function search(
array|ArrayAccess $array,
mixed $value,
?string $default = null,
bool $recursive = true,
string $delimiter = '.',
bool $strict = false
): string|bool|null {
if (! is_array($array) && ! $array instanceof ArrayAccess) {
throw new TypeException('First parameter must be an array or ArrayAccess object.');
}
if (null !== $default && ! is_int($default) && ! is_string($default)) {
throw new TypeException('Expects parameter 3 ($default) to be a string or integer or null.');
}
if (! is_string($delimiter)) {
throw new TypeException('Expects parameter 5 ($delimiter) to be a string.');
}
$key = array_search($value, $array, $strict);
if ($recursive && $key === false) {
$keys = [];
foreach ($array as $k => $v) {
if (is_array($v)) {
$rk = $this->search($v, $value, $default, true, $delimiter, $strict);
if ($rk !== $default) {
$keys = [$k, $rk];
break;
}
}
}
$key = count($keys) ? implode($delimiter, $keys) : false;
}
return $key === false ? $default : $key;
}
/**
* Returns only unique values in an array. It does not sort. First value is used.
*
* @param array $arr The array to dedupe.
* @return array array With only de-duped values.
*/
public function unique(array $arr): array
{
// filter out all duplicate values
return array_filter($arr, function ($item) {
// contrary to popular belief, this is not as static as you think...
static $vars = [];