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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
|
<?php
namespace StellarWP\Arrays;
use ArrayAccess; use Closure; use InvalidArgumentException;
/** * Array utilities */ class Arr { /** * Determines if the given value is array accessible. * * @param mixed $value * * @return bool */ public static function accessible( $value ): bool { return is_array( $value ) || $value instanceof ArrayAccess; }
/** * Add an element to an array using "dot" notation if it doesn't exist. * * @param array $array * @param string|int|float $key * @param mixed $value * * @return array */ public static function add( $array, $key, $value ) { $key = explode( '.', $key ); $key = static::wrap( $key ); if ( is_null( static::get( $array, $key ) ) ) { $array = static::set( $array, $key, $value ); }
return $array; }
/** * Duplicates any key not prefixed with '_' creating a prefixed duplicate one. * * The prefixing and duplication is recursive. * * @since 1.0.0 * * @param mixed $array The array whose keys should be duplicated. * @param bool $recursive Whether the prefixing and duplication should be * recursive or shallow. * * @return array|mixed The array with the duplicate, prefixed, keys or the * original input if not an array. */ public static function add_prefixed_keys_to( $array, bool $recursive = false ) { if ( ! is_array( $array ) ) { return $array; }
$prefixed = []; foreach ( $array as $key => $value ) { if ( $recursive && is_array( $value ) ) { $value = self::add_prefixed_keys_to( $value, true ); // And also add it to the original array. $array[ $key ] = array_merge( $array[ $key ], $value ); }
if ( 0 === strpos( $key, '_' ) ) { continue; }
$prefixed[ '_' . $key ] = $value; }
return array_merge( $array, $prefixed ); }
/** * Duplicates any key prefixed with '_' creating an un-prefixed duplicate one. * * The un-prefixing and duplication is recursive. * * @since 1.0.0 * * @param mixed $array The array whose keys should be duplicated. * @param bool $recursive Whether the un-prefixing and duplication should be * recursive or shallow. * * @return mixed|array The array with the duplicate, unprefixed, keys or the * original input if not an array. */ public static function add_unprefixed_keys_to( $array, bool $recursive = false ) { if ( ! is_array( $array ) ) { return $array; }
$unprefixed = []; foreach ( $array as $key => $value ) { if ( $recursive && is_array( $value ) ) { $value = self::add_unprefixed_keys_to( $value, true ); // And also add it to the original array. $array[ $key ] = array_merge( $array[ $key ], $value ); }
if ( 0 !== strpos( $key, '_' ) ) { continue; } $unprefixed[ substr( $key, 1 ) ] = $value; }
return array_merge( $array, $unprefixed ); }
/** * Recursively visits all elements of an array applying the specified callback to each element * key and value. * * @since 1.0.0 * * @param array|mixed $input The input array whose nodes should be visited. * @param callable $visitor A callback function that will be called on each array item; the callback will * receive the item key and value as input and should return an array that contains * the update key and value in the shape `[ <key>, <value> ]`. Returning a `null` * key will cause the element to be removed from the array. */ public static function array_visit_recursive( $input, callable $visitor ) { if ( ! is_array( $input ) ) { return $input; }
$return = [];
foreach ( $input as $key => &$value ) { if ( is_array( $value ) ) { $value = static::array_visit_recursive( $value, $visitor ); } // Ensure visitors can quickly return `null` to remove an element. [ $updated_key, $update_value ] = array_replace( [ $key, $value ], static::wrap( $visitor( $key, $value ) ) ); if ( false === $updated_key ) { // Visitor will be able to remove an element by returning a `false` key for it. continue; } if ( null === $updated_key ) { // Automatically assign the first available numeric index to the element. $return[] = $update_value; } else { $return[ $updated_key ] = $update_value; } }
return $return; }
/** * Collapse an array of arrays into a single array. * * @param iterable $array * * @return array */ public static function collapse( $array ) { $results = [];
foreach ( $array as $values ) { if ( ! is_array( $values ) ) { continue; }
$results[] = $values; }
return array_merge( [], ...$results ); }
/** * The inverse of the `stringify_keys` method, it will restore numeric keys for previously * stringified keys. * * @since 1.0.0 * * @param array<int|string,mixed> $input The input array whose stringified keys should be * destringified. * @param string $prefix The prefix that should be used to target only specific string keys. * * @return array<int|string,mixed> The input array, its stringified keys destringified. */ public static function destringify_keys( array $input, string $prefix = 'sk_' ): array { $visitor = static function( $key, $value ) use ( $prefix ) { $destringified_key = 0 === self::strpos( $key, $prefix ) ? null : $key;
return [ $destringified_key, $value ]; };
return static::array_visit_recursive( $input, $visitor ); }
/** * Flatten a multi-dimensional associative array with dots. * * @param iterable $array * @param string $prepend * * @return array */ public static function dot( $array, $prepend = '' ) { $results = [];
foreach ( $array as $key => $value ) { if ( is_array( $value ) ) { $results = array_merge( $results, static::dot( $value, $prepend . $key . '.' ) ); } else { $results[ $prepend . $key ] = $value; } }
return $results; }
/** * Sanitize a multidimensional array. * * @link https://gist.github.com/esthezia/5804445 * @since 1.0.0 * * @param array|mixed $data The array to sanitize. * * @return array The sanitized array * */ public static function escape_multidimensional_array( $data = [] ): array {
if ( ! is_array( $data ) || ! count( $data ) ) { return []; }
foreach ( $data as $key => $value ) { if ( ! is_array( $value ) && ! is_object( $value ) ) { $data[ $key ] = esc_attr( trim( $value ) ); } if ( is_array( $value ) ) { $data[ $key ] = self::escape_multidimensional_array( $value ); } }
return $data; }
/** * Discards everything other than array values having string keys and scalar values, ensuring a * one-dimensional, associative array result. * * @link https://www.php.net/manual/language.types.array.php Keys cast to non-strings will be discarded. * * @since 1.0.0 * * @param array|mixed $array * * @return array|mixed Associative or empty array. */ public static function filter_to_flat_scalar_associative_array( $array ) { $result = [];
if ( ! is_array( $array ) ) { return $result; }
foreach ( $array as $k => $v ) { if ( ! is_string( $k ) ) { continue; }
if ( ! is_scalar( $v ) ) { continue; }
$result[ $k ] = $v; }
return $result; }
/** * Get all of the given array except for a specified array of keys. * * @param array $array * @param array|string|int|float $keys * * @return array */ public static function except( $array, $keys ) { $new_array = $array; static::forget( $new_array, $keys );
return $new_array; }
/** * Determine if the given key exists in the provided array. * * @param \ArrayAccess|array $array * @param string|int|float $key * * @return bool */ public static function exists( $array, $key ) { return static::has( $array, $key ); }
/** * Filters an associative array non-recursively, keeping only the values attached * to keys starting with the specified prefix. * * @since 1.0.0 * * @param array $array The array to filter. * @param string $prefix The prefix, or prefixes, of the keys to keep. * * @return array The filtered array. */ public static function filter_prefixed( array $array, string $prefix ): array { $prefixes = implode( '|', array_map( 'preg_quote', static::wrap( $prefix ) ) ); $pattern = '/^(' . $prefixes . ')/'; $filtered = []; foreach ( $array as $key => $value ) { if ( ! preg_match( $pattern, $key ) ) { continue; } $filtered[ $key ] = $value; }
return $filtered; }
/** * Return the first element in an array passing a given truth test. * * @param iterable $array * @param callable|null $callback * @param mixed $default * * @return mixed */ public static function first( $array, callable $callback = null, $default = null ) { if ( is_null( $callback ) ) { if ( empty( $array ) ) { return self::value( $default ); }
foreach ( $array as $item ) { return $item; } }
foreach ( $array as $key => $value ) { if ( $callback( $value, $key ) ) { return $value; } }
return self::value( $default ); }
/** * Flatten a multi-dimensional array into a single level. * * Typical use case is to flatten arrays like those returned by `get_post_meta( $id )`. * Empty arrays are replaced with an empty string. * * @since 1.0.0 * * @param iterable $array * @param int $depth * * @return array The flattened array. */ public static function flatten( $array, int $depth = PHP_INT_MAX ): array { $result = [];
if ( $depth < 1 ) { return $array; }
foreach ( $array as $key => $item ) { if ( ! is_array( $item ) ) { // Preserve string keys, use numeric keys for numeric if ( is_string( $key ) ) { $result[ $key ] = $item; } else { $result[] = $item; } } else { $values = $depth === 1 ? array_values( $item ) : static::flatten( $item, $depth - 1 );
foreach ( $values as $value_key => $value ) { // Preserve string keys from nested arrays if ( is_string( $value_key ) ) { $result[ $value_key ] = $value; } else { $result[] = $value; } } } }
return $result; }
/** * Remove one or many array items from a given array using "dot" notation. * * @param array $array * @param array|string|int|float $keys * * @return void */ public static function forget( &$array, $keys ) { $keys = (array) $keys;
foreach ( $keys as $key ) { // Convert dot notation to array segments $parts = explode( '.', $key );
if ( count( $parts ) === 1 ) { unset( $array[ $key ] ); continue; }
// For nested keys, traverse the array $current = &$array; $lastKey = array_pop( $parts );
foreach ( $parts as $part ) { if ( ! isset( $current[ $part ] ) || ! is_array( $current[ $part ] ) ) { continue 2; } $current = &$current[ $part ]; }
unset( $current[ $lastKey ] ); } }
/** * Find a value inside of an array or object, including one nested a few levels deep. * * Example: get( $a, [ 0, 1, 2 ] ) returns the value of $a[0][1][2] or the default. * * @param array|object|mixed $variable Array or object to search within. * @param array|string|int|null $indexes Specify each nested index in order. Can also be in dot notation. * Example: array( 'lvl1', 'lvl2' ) or 'lvl1.lvl2'. * @param mixed $default Default value if the search finds nothing. * * @return mixed The value of the specified index or the default if not found. * @throws \InvalidArgumentException If the provided variable is not an array and does not implement ArrayAccess. */ public static function get( $variable, $indexes, $default = null ) { if ( ! static::accessible( $variable ) ) { throw new \InvalidArgumentException( 'The provided variable is not an array and does not implement ArrayAccess.' ); }
if ( is_null( $indexes ) ) { return $variable; }
if ( is_string( $indexes ) && isset( $variable[ $indexes ] ) ) { return $variable[ $indexes ]; } elseif ( is_string( $indexes ) ) { $indexes = explode( '.', $indexes ); }
$indexes = static::wrap( $indexes );
foreach ( $indexes as $index ) { if ( ! static::exists( $variable, $index ) ) { $variable = $default; break; }
$variable = $variable[ $index ]; }
return $variable; }
/** * Returns the value associated with the first index, among the indexes, that is set in the array.. * * @since 1.0.0 * * @param array $array The array to search. * @param array $indexes The indexes to search; in order the function will look from the first to the last. * @param mixed $default The value that will be returned if the array does not have any of the indexes set. * * @return mixed|null The set value or the default value. */ public static function get_first_set( array $array, array $indexes, $default = null ) { foreach ( $indexes as $index ) { if ( ! isset( $array[ $index ] ) ) { continue; }
return $array[ $index ]; }
return $default; }
/** * Find a value inside a list of array or objects, including one nested a few levels deep. * * @since 1.0.0 * * Example: get( [$a, $b, $c], [ 0, 1, 2 ] ) returns the value of $a[0][1][2] found in $a, $b or $c * or the default. * * @param array $variables Array of arrays or objects to search within. * @param array|string $indexes Specify each nested index in order. * Example: array( 'lvl1', 'lvl2' ); * @param mixed $default Default value if the search finds nothing. * * @return mixed The value of the specified index or the default if not found. */ public static function get_in_any( array $variables, $indexes, $default = null ) { foreach ( $variables as $variable ) { $found = self::get( $variable, $indexes, '__not_found__' ); if ( '__not_found__' !== $found ) { return $found; } }
return $default; }
/** * Check if an item or items exist in an array using "dot" notation. * * @param \ArrayAccess|array $array * @param array|string|int|null $indexes The indexes to search; in order the function will look from the first to the last. * * @return bool */ public static function has( $array, $indexes ) { if ( ! is_array( $array ) ) { return false; }
if ( isset( $array[ $indexes ] ) ) { return true; }
if ( is_string( $indexes ) && isset( $array[ $indexes ] ) ) { return true; }
if ( is_string( $indexes ) ) { $indexes = explode( '.', $indexes ); }
// Start with the root array $current = &$array;
// Get all segments except the last one $segments = array_slice( $indexes, 0, -1 ); $final_key = end( $indexes );
// Iterate through every key, setting the pointer one level deeper each time. foreach ( $segments as $segment ) { if ( ! isset( $current[ $segment ] ) || ! is_array( $current[ $segment ] ) ) { return false; } $current = &$current[ $segment ]; }
return isset( $current[ $final_key ] ); }
/** * Insert an array after a specified key within another array. * * @param string|int $key The key of the array to insert after. * @param array $source_array The array to insert into. * @param mixed $insert Value or array to insert. * * @return array */ public static function insert_after_key( $key, array $source_array, $insert ): array { if ( ! is_array( $insert ) ) { $insert = [ $insert ]; }
if ( array_key_exists( $key, $source_array ) ) { $position = array_search( $key, array_keys( $source_array ) ) + 1; $source_array = array_slice( $source_array, 0, $position, true ) + $insert + array_slice( $source_array, $position, null, true ); } else { // If no key is found, then add it to the end of the array. $source_array += $insert; }
return $source_array; }
/** * Insert an array immediately before a specified key within another array. * * @param string|int $key The key of the array to insert before. * @param array $source_array The array to insert into. * @param mixed $insert Value or array to insert. * * @return array */ public static function insert_before_key( $key, array $source_array, $insert ): array { if ( ! is_array( $insert ) ) { $insert = [ $insert ]; }
if ( array_key_exists( $key, $source_array ) ) { $position = array_search( $key, array_keys( $source_array ) ); $source_array = array_slice( $source_array, 0, $position, true ) + $insert + array_slice( $source_array, $position, null, true ); } else { // If no key is found, then add it to the end of the array. $source_array += $insert; }
return $source_array; }
/** * Determines if an array is associative. * * An array is "associative" if it doesn't have sequential numerical keys beginning with zero. * * @param array $array * * @return bool */ public static function is_assoc( array $array ) { return ! static::is_list( $array ); }
/** * Determines if an array is a list. * * An array is a "list" if all array keys are sequential integers starting from 0 with no gaps in between. * * @param array $array * * @return bool */ public static function is_list( $array ) { if ( function_exists( 'array_is_list' ) ) { return array_is_list( $array ); }
$i = 0; foreach ( $array as $k => $v ) { if ( $k !== $i++ ) { return false; } }
return true; }
/** * Join all items using a string. The final items can use a separate glue string. * * @param array $array * @param string $glue * @param string $finalGlue * * @return string */ public static function join( $array, $glue, $finalGlue = '' ) { if ( $finalGlue === '' ) { return implode( $glue, $array ); }
if ( count( $array ) === 0 ) { return ''; }
if ( count( $array ) === 1 ) { return end( $array ); }
$finalItem = array_pop( $array );
return implode( $glue, $array ) . $finalGlue . $finalItem; }
/** * Return the last element in an array passing a given truth test. * * @param array $array * @param callable|null $callback * @param mixed $default * * @return mixed */ public static function last( $array, callable $callback = null, $default = null ) { if ( is_null( $callback ) ) { return empty( $array ) ? self::value( $default ) : end( $array ); }
return static::first( array_reverse( $array, true ), $callback, $default ); }
/** * Converts a list to an array filtering out empty string elements. * * @param string|mixed|null $value A string representing a list of values separated by the specified separator * or an array. If the list is a string (e.g. a CSV list) then it will urldecoded * before processing. * @param string|mixed $sep The char(s) separating the list elements; will be ignored if the list is an array. * * @return array An array of list elements. */ public static function list_to_array( $value, $sep = ',' ): array { // Let's not jump through all the hoops if the value is empty. if ( empty( $value ) ) { return []; } // since we might receive URL encoded strings for CSV lists let's URL decode them first $value = is_array( $value ) ? $value : urldecode( $value );
$sep = ! is_string( $sep ) ? ',' : $sep;
if ( $value === '' ) { return []; }
if ( ! is_array( $value ) ) { $value = preg_split( '/\\s*' . preg_quote( $sep, '/' ) . '\\s*/', $value ); }
$filtered = []; foreach ( $value as $v ) { if ( '' === $v ) { continue; } $filtered[] = is_numeric( $v ) ? $v + 0 : $v; }
return $filtered; }
/** * Returns an array of values obtained by using the keys on the map; keys * that do not have a match in map are discarded. * * To discriminate from not found results and legitimately `false` * values from the map the `$found` parameter will be set by reference. * * @since 1.0.0 * * @param string|array $keys One or more keys that should be used to get * the new values * @param array $map An associative array relating the keys to the new * values. * @param bool $found When using a single key this argument will be * set to indicate whether the mapping was successful * or not. * * @return array|mixed|false An array of mapped values, a single mapped value when passing * one key only or `false` if one key was passed but the key could * not be mapped. */ public static function map_or_discard( $keys, array $map, bool &$found = true ) { $hash = md5( (string) time() ); $mapped = [];
foreach ( (array) $keys as $key ) { $meta_key = self::get( $map, $key, $hash ); if ( $hash === $meta_key ) { continue; } $mapped[] = $meta_key; }
$found = (bool) count( $mapped );
if ( is_array( $keys ) ) { return $mapped; }
return $found ? $mapped[0] : false; }
/** * Recursively merge two arrays preserving keys. * * @link http://php.net/manual/en/function.array-merge-recursive.php#92195 * * @since 1.0.0 * * @param array $array1 * @param array $array2 * * @return array */ public static function merge_recursive( array &$array1, array &$array2 ): array { $merged = $array1;
foreach ( $array2 as $key => &$value ) { if ( is_array( $value ) && isset( $merged[ $key ] ) && is_array( $merged[ $key ] ) ) { $merged[ $key ] = static::merge_recursive( $merged[ $key ], $value ); } else if ( is_int( $key ) ) { $merged[] = $value; } else { $merged[ $key ] = $value; } }
return $merged; }
/** * Merges two or more arrays in the nested format used by WP_Query arguments preserving and merging them correctly. * * The method will recursively replace named keys and merge numeric keys. The method takes its name from its intended * primary use, but it's not limited to query arguments only. * * @since 1.0.0 * * @param array<string|int,mixed> ...$arrays A set of arrays to merge. * * @return array<string|int,mixed> The recursively merged array. */ public static function merge_recursive_query_vars( array ...$arrays ): array { if ( ! count( $arrays ) ) { return []; }
// Temporarily transform numeric keys to string keys generated with time-related randomness. $stringified = array_map( [ static::class, 'stringify_keys' ], $arrays ); // Replace recursive will recursively replace any entry that has the same string key, stringified keys will never match due to randomness. $merged = array_replace_recursive( ...$stringified );
// Finally destringify the keys to return something that will resemble, in shape, the original arrays. return static::destringify_keys( $merged ); }
/** * Get a subset of the items from the given array. * * @param array $array * @param array|string $keys * * @return array */ public static function only( $array, $keys ) { return array_intersect_key( $array, array_flip( static::wrap( $keys ) ) ); }
/** * Build an array from migrating aliased key values to their canonical key values, removing all alias keys. * * If the original array has values for both the alias and its canonical, keep the canonical's value and * discard the alias' value. * * @since 1.0.0 * * @param array $original An associative array of values, such as passed shortcode arguments. * @param array $alias_map An associative array of aliases: key as alias, value as mapped canonical. * Example: [ 'alias' => 'canonical', 'from' => 'to', 'that' => 'becomes_this' ] * * @return array */ public static function parse_associative_array_alias( array $original, array $alias_map ): array { // Ensure array values. $alias_map = static::filter_to_flat_scalar_associative_array( $alias_map );
// Fail gracefully if alias array wasn't setup as [ 'from' => 'to' ]. if ( empty( $alias_map ) ) { return $original; }
$result = $original;
// Parse aliases. foreach ( $alias_map as $from => $to ) { // If this alias isn't in use, go onto the next. if ( ! isset( $result[ $from ] ) ) { continue; }
// Only allow setting alias value if canonical value is not already present. if ( ! isset( $result[ $to ] ) ) { $result[ $to ] = $result[ $from ]; }
// Always remove the alias key. unset( $result[ $from ] ); }
return $result; }
/** * Push an item onto the beginning of an array. * * @param array $array * @param mixed $value * @param mixed $key * * @return array */ public static function prepend( $array, $value, $key = null ) { if ( func_num_args() == 2 ) { array_unshift( $array, $value ); } else { $array = [ $key => $value ] + $array; }
return $array; }
/** * Get a value from the array, and remove it. * * @param array $array * @param string|int $key * @param mixed $default * * @return mixed */ public static function pull( &$array, $key, $default = null ) { $value = static::get( $array, $key, $default );
static::forget( $array, $key );
return $value; }
/** * Convert the array into a query string. * * @param array $array * * @return string */ public static function query( $array ) { return http_build_query( $array, '', '&', PHP_QUERY_RFC3986 ); }
/** * Get one or a specified number of random values from an array. * * @param array $array * @param int|null $number * @param bool $preserveKeys * * @return mixed * * @throws \InvalidArgumentException */ public static function random( $array, $number = null, $preserveKeys = false ) { $requested = is_null( $number ) ? 1 : $number;
$count = count( $array );
if ( $requested > $count ) { throw new InvalidArgumentException( "You requested {$requested} items, but there are only {$count} items available." ); }
if ( is_null( $number ) ) { return $array[ array_rand( $array ) ]; }
if ( (int) $number === 0 ) { return []; }
$keys = array_rand( $array, $number ); $keys = static::wrap( $keys );
$results = [];
if ( $preserveKeys ) { foreach ( $keys as $key ) { $results[ $key ] = $array[ $key ]; } } else { foreach ( $keys as $key ) { $results[] = $array[ $key ]; } }
return $results; }
/** * Recursively key-sort an array. * * @since 1.0.0 * * @param array $array The array to sort, modified by reference. * * @return bool The sorting result. */ public static function recursive_ksort( array &$array ): bool { // First recursively sort all sub-arrays foreach ( $array as &$value ) { if ( is_array( $value ) ) { static::recursive_ksort( $value ); } }
// Then sort the current array, ensuring numeric keys are sorted numerically return ksort( $array, SORT_NATURAL ); }
/** * Recursively remove numeric keys from an array. * * @since 1.0.0 * * @param array<string|int,mixed> $input The input array. * * @return array<int|mixed> An array that only contains integer keys at any of its levels. */ public static function remove_numeric_keys_recursive( array $input ): array { return self::array_visit_recursive( $input, static function( $key ) { return is_numeric( $key ) ? false : $key; } ); }
/** * Recursively remove numeric keys from an array. * * @since 1.0.0 * * @param array<string|int,mixed> $input The input array. * * @return array<string,mixed> An array that only contains non numeric keys at any of its levels. */ public static function remove_string_keys_recursive( array $input ): array { return self::array_visit_recursive( $input, static function( $key ) { return ! is_numeric( $key ) ? false : $key; } ); }
/** * Set key/value within an array, can set a key nested inside of a multidimensional array. * * Example: set( $a, [ 0, 1, 2 ], 'hi' ) sets $a[0][1][2] = 'hi' and returns $a. * * @param mixed $array The array containing the key this sets. * @param string|array $key To set a key nested multiple levels deep pass an array * specifying each key in order as a value. * Example: array( 'lvl1', 'lvl2', 'lvl3' ); * @param mixed $value The value. * * @return array Full array with the key set to the specified value. */ public static function set( $array, $key, $value ): array { // Convert input to array if not already if ( ! is_array( $array ) ) { $array = []; }
// If key is a string with dots, convert to array if ( is_string( $key ) ) { $key = explode( '.', $key ); }
// Convert strings and such to array. $key = static::wrap( $key );
// Start with the root array $current = &$array;
// Get all segments except the last one $segments = array_slice( $key, 0, -1 ); $final_key = end( $key );
// Traverse through each key segment foreach ( $segments as $segment ) { // If the current segment is a Closure or not an array, convert it to an array if ( ! isset( $current[ $segment ] ) || ! is_array( $current[ $segment ] ) ) { $current[ $segment ] = []; }
// Move pointer to next level $current = &$current[ $segment ]; }
// Set the final value $current[ $final_key ] = $value;
return $array; }
/** * Shapes, filtering it, an array to the specified expected set of required keys. * * @since 1.0.0 * * @param array $array The input array to shape. * @param array $shape The shape to update the array with. It should only define keys * or arrays of keys. Keys that have no values will be set to `null`. * To add the key only if set, prefix the key with `?`, e.g. `?foo`. * * @return array The input array shaped and ordered per the shape. */ public static function shape_filter( array $array, array $shape ): array { $shaped = []; foreach ( $shape as $shape_index => $shape_key ) { $optional = is_array( $shape_key ) ? strpos( $shape_index, '?' ) === 0 : strpos( $shape_key, '?' ) === 0;
if ( is_array( $shape_key ) ) { $shape_index = $optional ? substr( $shape_index, 1 ) : $shape_index; if ( $optional && ! isset( $array[ $shape_index ] ) ) { continue; } $shaped[ $shape_index ] = self::shape_filter( $array[ $shape_index ] ?? [], $shape_key ); } else { $shape_key = $optional ? substr( $shape_key, 1 ) : $shape_key; if ( ! isset( $array[ $shape_key ] ) && $optional ) { continue; } $shaped[ $shape_key ] = $array[ $shape_key ] ?? null; } }
return $shaped; }
/** * Shuffle the given array and return the result. * * @param array $array * @param int|null $seed * * @return array */ public static function shuffle( $array, $seed = null ) { if ( is_null( $seed ) ) { shuffle( $array ); } else { mt_srand( $seed ); shuffle( $array ); mt_srand(); }
return $array; }
/** * Sort based on Priority * * @since 1.0.0 * * @param array $array Array to sort. * * @return array */ public static function sort_by_priority( $array ): array { if ( ! is_array( $array ) ) { throw new \InvalidArgumentException( 'Input must be an array' ); }
if ( static::is_assoc( $array ) ) { uasort( $array, [ static::class, 'sort_by_priority_comparison' ] ); } else { usort( $array, [ static::class, 'sort_by_priority_comparison' ] ); }
return $array; }
/** * Sort based on Priority * * @since 1.0.0 * * @param object|array $b Second subject to compare * * @param object|array $a First Subject to compare * * @return int */ public static function sort_by_priority_comparison( $a, $b ): int { if ( is_array( $a ) ) { $a_priority = $a['priority']; } else { $a_priority = $a->priority; }
if ( is_array( $b ) ) { $b_priority = $b['priority']; } else { $b_priority = $b->priority; }
if ( (int) $a_priority === (int) $b_priority ) { return 0; }
return (int) $a_priority > (int) $b_priority ? 1 : -1; }
/** * Recursively sort an array by keys and values. * * @param array $array * @param int $options * @param bool $descending * * @return array */ public static function sort_recursive( $array, $options = SORT_REGULAR, $descending = false ) { foreach ( $array as &$value ) { if ( is_array( $value ) ) { $value = static::sort_recursive( $value, $options, $descending ); } }
if ( ! static::is_list( $array ) ) { $descending ? krsort( $array, $options ) : ksort( $array, $options ); } else { $descending ? rsort( $array, $options ) : sort( $array, $options ); }
return $array; }
/** * Recursively sort an array by keys and values in descending order. * * @param array $array * @param int $options * * @return array */ public static function sort_recursive_desc( $array, $options = SORT_REGULAR ) { return static::sort_recursive( $array, $options, true ); }
/** * Stringifies the numeric keys of an array. * * @since 1.0.0 * * @param array<int|string,mixed> $input The input array whose keys should be stringified. * @param string|null $prefix The prefix that should be use to stringify the keys, if not provided * then it will be generated. * * @return array<string,mixed> The input array with each numeric key stringified. */ public static function stringify_keys( array $input, $prefix = null ): array { $prefix = null === $prefix ? uniqid( 'sk_' ) : $prefix; $visitor = static function( $key, $value ) use ( $prefix ) { $string_key = is_numeric( $key ) ? $prefix . $key : $key;
return [ $string_key, $value ]; };
return static::array_visit_recursive( $input, $visitor ); }
/** * Behaves exactly like the native strpos(), but accepts an array of needles. * * @see strpos() * * @param string $haystack String to search in. * @param array|string $needles Strings to search for. * @param int $offset Starting position of search. * * @return false|int Integer position of first needle occurrence. */ public static function strpos( string $haystack, $needles, int $offset = 0 ) { $needles = static::wrap( $needles );
$needles = array_filter( $needles, static function( $needle ) { return is_string( $needle ) && $needle !== ''; } );
foreach ( $needles as $i ) { $search = strpos( $haystack, $i, $offset );
if ( false !== $search ) { return $search; } }
return false; }
/** * Returns a list separated by the specified separator. * * @since 1.0.0 * * @param mixed $list * @param string $sep * * @return string The list separated by the specified separator or the original list if the list is empty. */ public static function to_list( $list, string $sep = ',' ): string { if ( $list === null ) { return ''; }
if ( empty( $list ) ) { return is_array( $list ) ? '' : $list; }
if ( is_array( $list ) ) { return implode( $sep, $list ); }
return $list; }
/** * Convert a flatten "dot" notation array into an expanded array. * * @param iterable $array * * @return array */ public static function undot( $array ) { $results = [];
foreach ( $array as $key => $value ) { $results = static::set( $results, explode( '.', $key ), $value ); }
return $results; }
/** * Searches an array using a callback and returns the index of the first match. * * This method fills the gap left by the non-existence of an `array_usearch` function. * * @since 1.0.0 * * @param mixed $needle The element to search in the array. * @param array $haystack The array to search. * @param callable $callback A callback function with signature `fn($needle, $value, $key) :bool` * that will be used to find the first match of needle in haystack. * * @return string|int|false Either the index of the first match or `false` if no match was found. */ public static function usearch( $needle, array $haystack, callable $callback ) { foreach ( $haystack as $key => $value ) { if ( $callback( $needle, $value, $key ) ) { return $key; } }
return false; }
/** * Filter the array using the given callback. * * @param array $array * @param callable $callback * * @return array */ public static function where( $array, callable $callback ) { return array_filter( $array, $callback, ARRAY_FILTER_USE_BOTH ); }
/** * Filter items where the value is not null. * * @param array $array * * @return array */ public static function where_not_null( $array ) { return static::where( $array, static function( $value ) { return ! is_null( $value ); } ); }
/** * If the given value is not an array and not null, wrap it in one. * * @param mixed $value * * @return array */ public static function wrap( $value ) { if ( is_null( $value ) ) { return []; }
return is_array( $value ) ? $value : [ $value ]; }
/** * Recursively computes the intersection of arrays using keys for comparison. * * @param mixed[] $array The array with master keys to check. * @param mixed[] ...$arrays Additional arrays to compare keys against. * * @return mixed[] An associative array containing all the entries of $array * whose keys exist in every provided array, recursively. */ public static function intersect_key_recursive( array $array, array ...$arrays ): array { $array = array_intersect_key( $array, ...$arrays );
foreach ( $array as $key => $value ) { if ( ! is_array( $value ) ) { continue; }
$arrays_to_intersect = []; foreach ( $arrays as $intersect_array ) { if ( ! isset( $intersect_array[ $key ] ) ) { unset( $array[ $key ] ); continue 2; }
if ( ! is_array( $intersect_array[ $key ] ) ) { continue; }
$arrays_to_intersect[] = $intersect_array[ $key ]; }
if ( empty( $arrays_to_intersect ) ) { continue; }
$array[ $key ] = static::intersect_key_recursive( $value, ...$arrays_to_intersect ); }
return $array; }
/** * Return the default value of the given value. * * @template TValue * @template TArgs * * @param TValue|\Closure(TArgs): TValue $value * @param TArgs ...$args * @return TValue */ private static function value( $value, ...$args ) { return $value instanceof Closure ? $value( ...$args ) : $value; } }
|