3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Provides a collection of static methods for array manipulation.
16 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 class CRM_Utils_Array
{
21 * Returns $list[$key] if such element exists, or a default value otherwise.
23 * If $list is not actually an array at all, then the default value is
24 * returned. We hope to deprecate this behaviour.
28 * Key value to look up in the array.
29 * @param array|ArrayAccess $list
30 * Array from which to look up a value.
31 * @param mixed $default
32 * (optional) Value to return $list[$key] does not exist.
35 * Can return any type, since $list might contain anything.
37 public static function value($key, $list, $default = NULL) {
38 if (is_array($list)) {
39 return array_key_exists($key, $list) ?
$list[$key] : $default;
41 if ($list instanceof ArrayAccess
) {
42 // ArrayAccess requires offsetExists is implemented for the equivalent to array_key_exists.
43 return $list->offsetExists($key) ?
$list[$key] : $default;
45 // @todo - eliminate these from core & uncomment this line.
46 // CRM_Core_Error::deprecatedFunctionWarning('You have passed an invalid parameter for the "list"');
51 * Recursively searches an array for a key, returning the first value found.
53 * If $params[$key] does not exist and $params contains arrays, descend into
54 * each array in a depth-first manner, in array iteration order.
56 * @param array $params
57 * The array to be searched.
59 * The key to search for.
62 * The value of the key, or null if the key is not found.
64 public static function retrieveValueRecursive(array $params, string $key) {
65 // Note that !empty means funky handling for 0
66 // but it is 'baked in'. We should probably deprecate this
67 // for a more logical approach.
68 // see https://github.com/civicrm/civicrm-core/pull/19478#issuecomment-785388559
69 if (!empty($params[$key])) {
72 foreach ($params as $subParam) {
73 if (is_array($subParam) &&
74 // @todo - this will mishandle values like 0 and false
75 // but it's a little scary to fix.
76 $value = self
::retrieveValueRecursive($subParam, $key)
85 * Recursively searches through a given array for all matches
91 public static function findAll($collection, $predicate) {
93 $search = function($collection) use (&$search, &$results, $predicate) {
94 if (is_array($collection)) {
95 if (is_callable($predicate)) {
96 if ($predicate($collection)) {
97 $results[] = $collection;
100 elseif (is_array($predicate)) {
101 if (count(array_intersect_assoc($collection, $predicate)) === count($predicate)) {
102 $results[] = $collection;
106 if (array_key_exists($predicate, $collection)) {
107 $results[] = $collection;
110 foreach ($collection as $item) {
115 $search($collection);
120 * Wraps and slightly changes the behavior of PHP's array_search().
122 * This function reproduces the behavior of array_search() from PHP prior to
123 * version 4.2.0, which was to return NULL on failure. This function also
124 * checks that $list is an array before attempting to search it.
127 * @param mixed $value
128 * The value to search for.
130 * The array to be searched.
132 * @return int|string|null
133 * Returns the key, which could be an int or a string, or NULL on failure.
135 public static function key($value, $list) {
136 if (is_array($list)) {
137 $key = array_search($value, $list);
139 // array_search returns key if found, false otherwise
140 // it may return values like 0 or empty string which
141 // evaluates to false
142 // hence we must use identical comparison operator
143 return ($key === FALSE) ?
NULL : $key;
149 * Builds an XML fragment representing an array.
151 * Depending on the nature of the keys of the array (and its sub-arrays,
152 * if any) the XML fragment may not be valid.
155 * The array to be serialized.
157 * (optional) Indentation depth counter.
158 * @param string $separator
159 * (optional) String to be appended after open/close tags.
162 * XML fragment representing $list.
164 public static function &xml(&$list, $depth = 1, $separator = "\n") {
166 foreach ($list as $name => $value) {
167 $xml .= str_repeat(' ', $depth * 4);
168 if (is_array($value)) {
169 $xml .= "<{$name}>{$separator}";
170 $xml .= self
::xml($value, $depth +
1, $separator);
171 $xml .= str_repeat(' ', $depth * 4);
172 $xml .= "</{$name}>{$separator}";
175 // make sure we escape value
176 $value = self
::escapeXML($value);
177 $xml .= "<{$name}>$value</{$name}>{$separator}";
184 * Sanitizes a string for serialization in CRM_Utils_Array::xml().
186 * Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A'
189 * @param string $value
190 * String to be sanitized.
193 * Sanitized version of $value.
195 public static function escapeXML($value) {
200 $src = ['&', '<', '>', '\ 1'];
201 $dst = ['&', '<', '>', ','];
204 return str_replace($src, $dst, $value);
208 * Converts a nested array to a flat array.
210 * The nested structure is preserved in the string values of the keys of the
213 * Example nested array:
238 * Corresponding flattened array:
244 * [asdf.merp] => bleep
245 * [asdf.quack.0] => 1
246 * [asdf.quack.1] => 2
247 * [asdf.quack.2] => 3
252 * Array to be flattened.
255 * @param string $prefix
256 * (optional) String to prepend to keys.
257 * @param string $separator
258 * (optional) String that separates the concatenated keys.
260 public static function flatten(&$list, &$flat, $prefix = '', $separator = ".") {
261 foreach ($list as $name => $value) {
262 $newPrefix = ($prefix) ?
$prefix . $separator . $name : $name;
263 if (is_array($value)) {
264 self
::flatten($value, $flat, $newPrefix, $separator);
267 $flat[$newPrefix] = $value;
273 * Converts an array with path-like keys into a tree of arrays.
275 * This function is the inverse of CRM_Utils_Array::flatten().
277 * @param string $delim
280 * A one-dimensional array indexed by string keys
285 public function unflatten($delim, &$arr) {
287 foreach ($arr as $key => $value) {
288 $path = explode($delim, $key);
290 while (count($path) > 1) {
291 $key = array_shift($path);
292 if (!isset($node[$key])) {
295 $node = &$node[$key];
298 $key = array_shift($path);
299 $node[$key] = $value;
307 * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge
308 * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both
309 * exist but they are not both arrays, the value from $a1 overrides the
310 * value from $a2 and the value from $a2 is discarded.
313 * First array to be merged.
315 * Second array to be merged.
320 public static function crmArrayMerge($a1, $a2) {
330 foreach ($a1 as $key => $value) {
331 if (array_key_exists($key, $a2) &&
332 is_array($a2[$key]) && is_array($a1[$key])
334 $a3[$key] = array_merge($a1[$key], $a2[$key]);
337 $a3[$key] = $a1[$key];
341 foreach ($a2 as $key => $value) {
342 if (array_key_exists($key, $a1)) {
343 // already handled in above loop
346 $a3[$key] = $a2[$key];
353 * Determines whether an array contains any sub-arrays.
356 * The array to inspect.
359 * True if $list contains at least one sub-array, false otherwise.
361 public static function isHierarchical(&$list) {
362 foreach ($list as $n => $v) {
371 * Is array A a subset of array B.
373 * @param array $subset
374 * @param array $superset
377 * TRUE if $subset is a subset of $superset
379 public static function isSubset($subset, $superset) {
380 foreach ($subset as $expected) {
381 if (!in_array($expected, $superset)) {
389 * Searches an array recursively in an optionally case-insensitive manner.
391 * @param string $value
392 * Value to search for.
393 * @param array $params
394 * Array to search within.
395 * @param bool $caseInsensitive
396 * (optional) Whether to search in a case-insensitive manner.
399 * True if $value was found, false otherwise.
401 public static function crmInArray($value, $params, $caseInsensitive = TRUE) {
402 foreach ($params as $item) {
403 if (is_array($item)) {
404 $ret = self
::crmInArray($value, $item, $caseInsensitive);
407 $ret = ($caseInsensitive) ?
strtolower($item) == strtolower($value) : $item == $value;
417 * Convert associative array names to values and vice-versa.
419 * This function is used by by import functions and some webforms.
421 * @param array $defaults
422 * @param string $property
428 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
429 $id = $property . '_id';
431 $src = $reverse ?
$property : $id;
432 $dst = $reverse ?
$id : $property;
434 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER
))) {
438 $look = $reverse ?
array_flip($lookup) : $lookup;
440 // trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
442 foreach ($look as $k => $v) {
443 $newLook[trim($k, ".")] = $v;
448 if (is_array($look)) {
449 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER
))) {
454 $tempLook = array_change_key_case($look, CASE_LOWER
);
456 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
461 * Checks whether an array is empty.
463 * An array is empty if its values consist only of NULL and empty sub-arrays.
464 * Containing a non-NULL value or non-empty array makes an array non-empty.
466 * If something other than an array is passed, it is considered to be empty.
468 * If nothing is passed at all, the default value provided is empty.
470 * @param array $array
471 * (optional) Array to be checked for emptiness.
474 * True if the array is empty.
476 public static function crmIsEmptyArray($array = []) {
477 if (!is_array($array)) {
480 foreach ($array as $element) {
481 if (is_array($element)) {
482 if (!self
::crmIsEmptyArray($element)) {
486 elseif (isset($element)) {
494 * Sorts an associative array of arrays by an attribute using strnatcmp().
496 * @param array $array
497 * Array to be sorted.
498 * @param string|array $field
499 * Name of the attribute used for sorting.
504 public static function crmArraySortByField($array, $field) {
505 $fields = (array) $field;
506 uasort($array, function ($a, $b) use ($fields) {
507 foreach ($fields as $f) {
508 $v = strnatcmp($a[$f], $b[$f]);
519 * Recursively removes duplicate values from a multi-dimensional array.
521 * @param array $array
522 * The input array possibly containing duplicate values.
525 * The input array with duplicate values removed.
527 public static function crmArrayUnique($array) {
528 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
529 foreach ($result as $key => $value) {
530 if (is_array($value)) {
531 $result[$key] = self
::crmArrayUnique($value);
538 * Sorts an array and maintains index association (with localization).
540 * Uses Collate from the PECL "intl" package, if available, for UTF-8
541 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
543 * On Debian/Ubuntu: apt-get install php5-intl
545 * @param array $array
546 * (optional) Array to be sorted.
551 public static function asort($array = []) {
552 $lcMessages = CRM_Utils_System
::getUFLocale();
554 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
555 $collator = new Collator($lcMessages . '.utf8');
556 $collator->asort($array);
559 // This calls PHP's built-in asort().
567 * Unsets an arbitrary list of array elements from an associative array.
569 * @param array $items
570 * The array from which to remove items.
573 * When passed a string, unsets $items[$key].
574 * When passed an array of strings, unsets $items[$k] for each string $k in the array.
576 public static function remove(&$items) {
577 foreach (func_get_args() as $n => $key) {
578 // Skip argument 0 ($items) by testing $n for truth.
579 if ($n && is_array($key)) {
580 foreach ($key as $k) {
591 * Builds an array-tree which indexes the records in an array.
593 * @param string[] $keys
594 * Properties by which to index.
595 * @param object|array $records
598 * Multi-dimensional array, with one layer for each key.
600 public static function index($keys, $records) {
601 $final_key = array_pop($keys);
604 foreach ($records as $record) {
606 foreach ($keys as $key) {
607 if (is_array($record)) {
608 $keyvalue = $record[$key] ??
NULL;
611 $keyvalue = $record->{$key} ??
NULL;
613 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
614 $node[$keyvalue] = [];
616 $node = &$node[$keyvalue];
618 if (is_array($record)) {
619 $node[$record[$final_key]] = $record;
622 $node[$record->{$final_key}] = $record;
629 * Iterates over a list of records and returns the value of some property.
631 * @param string $prop
632 * Property to retrieve.
633 * @param array|object $records
637 * Keys are the original keys of $records; values are the $prop values.
639 public static function collect($prop, $records) {
641 if (is_array($records)) {
642 foreach ($records as $key => $record) {
643 if (is_object($record)) {
644 $result[$key] = $record->{$prop};
647 $result[$key] = self
::value($prop, $record);
655 * Iterates over a list of objects and executes some method on each.
658 * - This is like array_map(), except it executes the objects' method
659 * instead of a free-form callable.
660 * - This is like Array::collect(), except it uses a method
661 * instead of a property.
663 * @param string $method
664 * The method to execute.
665 * @param array|Traversable $objects
668 * An optional list of arguments to pass to the method.
671 * Keys are the original keys of $objects; values are the method results.
673 public static function collectMethod($method, $objects, $args = []) {
675 if (is_array($objects)) {
676 foreach ($objects as $key => $object) {
677 $result[$key] = call_user_func_array([$object, $method], $args);
684 * Trims delimiters from a string and then splits it using explode().
686 * This method works mostly like PHP's built-in explode(), except that
687 * surrounding delimiters are trimmed before explode() is called.
689 * Also, if an array or NULL is passed as the $values parameter, the value is
690 * returned unmodified rather than being passed to explode().
692 * @param array|null|string $values
693 * The input string (or an array, or NULL).
694 * @param string $delim
695 * (optional) The boundary string.
698 * An array of strings produced by explode(), or the unmodified input
701 public static function explodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
702 if ($values === NULL) {
705 // If we already have an array, no need to continue
706 if (is_array($values)) {
709 // Empty string -> empty array
710 if ($values === '') {
713 return explode($delim, trim((string) $values, $delim));
717 * Joins array elements with a string, adding surrounding delimiters.
719 * This method works mostly like PHP's built-in implode(), but the generated
720 * string is surrounded by delimiter characters. Also, if NULL is passed as
721 * the $values parameter, NULL is returned.
723 * @param mixed $values
724 * Array to be imploded. If a non-array is passed, it will be cast to an
726 * @param string $delim
727 * Delimiter to be used for implode() and which will surround the output
730 * @return string|NULL
731 * The generated string, or NULL if NULL was passed as $values parameter.
733 public static function implodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
734 if ($values === NULL) {
737 // If we already have a string, strip $delim off the ends so it doesn't get added twice
738 if (is_string($values)) {
739 $values = trim($values, $delim);
741 return $delim . implode($delim, (array) $values) . $delim;
745 * Modifies a key in an array while preserving the key order.
747 * By default when an element is added to an array, it is added to the end.
748 * This method allows for changing an existing key while preserving its
749 * position in the array.
751 * The array is both modified in-place and returned.
753 * @param array $elementArray
754 * Array to manipulate.
755 * @param string $oldKey
756 * Old key to be replaced.
757 * @param string $newKey
758 * Replacement key string.
761 * Throws a generic Exception if $oldKey is not found in $elementArray.
764 * The manipulated array.
766 public static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
767 $keys = array_keys($elementArray);
768 if (FALSE === $index = array_search($oldKey, $keys)) {
769 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
771 $keys[$index] = $newKey;
772 $elementArray = array_combine($keys, array_values($elementArray));
773 return $elementArray;
777 * Searches array keys by regex, returning the value of the first match.
779 * Given a regular expression and an array, this method searches the keys
780 * of the array using the regular expression. The first match is then used
781 * to index into the array, and the associated value is retrieved and
782 * returned. If no matches are found, or if something other than an array
783 * is passed, then a default value is returned. Unless otherwise specified,
784 * the default value is NULL.
786 * @param string $regexKey
787 * The regular expression to use when searching for matching keys.
789 * The array whose keys will be searched.
790 * @param mixed $default
791 * (optional) The default value to return if the regex does not match an
792 * array key, or if something other than an array is passed.
797 public static function valueByRegexKey($regexKey, $list, $default = NULL) {
798 if (is_array($list) && $regexKey) {
799 $matches = preg_grep($regexKey, array_keys($list));
800 $key = reset($matches);
801 return ($key && array_key_exists($key, $list)) ?
$list[$key] : $default;
807 * Generates the Cartesian product of zero or more vectors.
809 * @param array $dimensions
810 * List of dimensions to multiply.
811 * Each key is a dimension name; each value is a vector.
812 * @param array $template
813 * (optional) A base set of values included in every output.
816 * Each item is a distinct combination of values from $dimensions.
818 * For example, the product of
821 * bg => {white, black}
825 * {fg => red, bg => white},
826 * {fg => red, bg => black},
827 * {fg => blue, bg => white},
828 * {fg => blue, bg => black}
831 public static function product($dimensions, $template = []) {
832 if (empty($dimensions)) {
836 foreach ($dimensions as $key => $value) {
838 $firstValues = $value;
841 unset($dimensions[$key]);
844 foreach ($firstValues as $firstValue) {
845 foreach (self
::product($dimensions, $template) as $result) {
846 $result[$firstKey] = $firstValue;
847 $results[] = $result;
855 * Get the first element of an array.
857 * @param array $array
860 public static function first($array) {
861 foreach ($array as $value) {
868 * Extract any $keys from $array and copy to a new array.
870 * Note: If a $key does not appear in $array, then it will
871 * not appear in the result.
873 * @param array $array
875 * List of keys to copy.
878 public static function subset($array, $keys) {
880 foreach ($keys as $key) {
881 if (isset($array[$key])) {
882 $result[$key] = $array[$key];
889 * Transform an associative array of key=>value pairs into a non-associative array of arrays.
890 * This is necessary to preserve sort order when sending an array through json_encode.
892 * @param array $associative
893 * Ex: ['foo' => 'bar'].
894 * @param string $keyName
896 * @param string $valueName
899 * Ex: [0 => ['key' => 'foo', 'value' => 'bar']].
901 public static function makeNonAssociative($associative, $keyName = 'key', $valueName = 'value') {
903 foreach ($associative as $key => $val) {
904 $output[] = [$keyName => $key, $valueName => $val];
910 * Diff multidimensional arrays
911 * (array_diff does not support multidimensional array)
913 * @param array $array1
914 * @param array $array2
917 public static function multiArrayDiff($array1, $array2) {
919 foreach ($array1 as $mKey => $mValue) {
920 if (array_key_exists($mKey, $array2)) {
921 if (is_array($mValue)) {
922 $recursiveDiff = self
::multiArrayDiff($mValue, $array2[$mKey]);
923 if (count($recursiveDiff)) {
924 $arrayDiff[$mKey] = $recursiveDiff;
928 if ($mValue != $array2[$mKey]) {
929 $arrayDiff[$mKey] = $mValue;
934 $arrayDiff[$mKey] = $mValue;
941 * Given a 2-dimensional matrix, create a new matrix with a restricted list of columns.
943 * @param array $matrix
944 * All matrix data, as a list of rows.
945 * @param array $columns
946 * List of column names.
949 public static function filterColumns($matrix, $columns) {
951 foreach ($matrix as $pos => $oldRow) {
953 foreach ($columns as $column) {
954 $newRow[$column] = $oldRow[$column] ??
NULL;
956 $newRows[$pos] = $newRow;
962 * Rewrite the keys in an array.
964 * @param array $array
965 * @param string|callable $indexBy
966 * Either the value to key by, or a function($key, $value) that returns the new key.
969 public static function rekey($array, $indexBy) {
971 foreach ($array as $key => $value) {
972 $newKey = is_callable($indexBy) ?
$indexBy($key, $value) : $value[$indexBy];
973 $result[$newKey] = $value;
979 * Copy all properties of $other into $array (recursively).
981 * @param array|ArrayAccess $array
982 * @param array $other
984 public static function extend(&$array, $other) {
985 foreach ($other as $key => $value) {
986 if (is_array($value)) {
987 self
::extend($array[$key], $value);
990 $array[$key] = $value;
996 * Get a single value from an array-tree.
998 * @param array $values
999 * Ex: ['foo' => ['bar' => 123]].
1000 * @param array $path
1001 * Ex: ['foo', 'bar'].
1002 * @param mixed $default
1006 public static function pathGet($values, $path, $default = NULL) {
1007 foreach ($path as $key) {
1008 if (!is_array($values) ||
!isset($values[$key])) {
1011 $values = $values[$key];
1017 * Check if a key isset which may be several layers deep.
1019 * This is a helper for when the calling function does not know how many layers deep
1020 * the path array is so cannot easily check.
1022 * @param array $values
1023 * @param array $path
1026 public static function pathIsset($values, $path) {
1027 foreach ($path as $key) {
1028 if (!is_array($values) ||
!isset($values[$key])) {
1031 $values = $values[$key];
1037 * Set a single value in an array tree.
1039 * @param array $values
1040 * Ex: ['foo' => ['bar' => 123]].
1041 * @param array $pathParts
1042 * Ex: ['foo', 'bar'].
1046 public static function pathSet(&$values, $pathParts, $value) {
1048 $last = array_pop($pathParts);
1049 foreach ($pathParts as $part) {
1050 if (!isset($r[$part])) {
1059 * Convert a simple dictionary into separate key+value records.
1061 * @param array $array
1062 * Ex: array('foo' => 'bar').
1063 * @param string $keyField
1065 * @param string $valueField
1070 public static function toKeyValueRows($array, $keyField = 'key', $valueField = 'value') {
1071 return self
::makeNonAssociative($array, $keyField, $valueField);
1075 * Convert array where key(s) holds the actual value and value(s) as 1 into array of actual values
1076 * Ex: array('foobar' => 1, 4 => 1) formatted into array('foobar', 4)
1078 * @deprecated use convertCheckboxInputToArray instead (after testing)
1079 * https://github.com/civicrm/civicrm-core/pull/8169
1081 * @param array $array
1083 public static function formatArrayKeys(&$array) {
1084 if (!is_array($array)) {
1087 $keys = array_keys($array, 1);
1088 if (count($keys) > 1 ||
1089 (count($keys) == 1 &&
1090 (current($keys) > 1 ||
1091 is_string(current($keys)) ||
1092 // handle (0 => 4), (1 => 1)
1093 (current($keys) == 1 && $array[1] == 1)
1102 * Convert the data format coming in from checkboxes to an array of values.
1104 * The input format from check boxes looks like
1105 * array('value1' => 1, 'value2' => 1). This function converts those values to
1106 * array(''value1', 'value2).
1108 * The function will only alter the array if all values are equal to 1.
1110 * @param array $input
1114 public static function convertCheckboxFormatToArray($input) {
1115 if (isset($input[0])) {
1118 $keys = array_keys($input, 1);
1119 if ((count($keys) == count($input))) {
1126 * Ensure that array is encoded in utf8 format.
1128 * @param array $array
1130 * @return array $array utf8-encoded.
1132 public static function encode_items($array) {
1133 foreach ($array as $key => $value) {
1134 if (is_array($value)) {
1135 $array[$key] = self
::encode_items($value);
1137 elseif (is_string($value)) {
1138 $array[$key] = mb_convert_encoding($value, mb_detect_encoding($value, mb_detect_order(), TRUE), 'UTF-8');
1141 $array[$key] = $value;
1148 * Build tree of elements.
1150 * @param array $elements
1151 * @param int|null $parentId
1155 public static function buildTree($elements, $parentId = NULL) {
1158 foreach ($elements as $element) {
1159 if ($element['parent_id'] == $parentId) {
1160 $children = self
::buildTree($elements, $element['id']);
1162 $element['children'] = $children;
1164 $branch[] = $element;
1172 * Find search string in tree.
1174 * @param string $search
1175 * @param array $tree
1176 * @param string $field
1178 * @return array|null
1180 public static function findInTree($search, $tree, $field = 'id') {
1181 foreach ($tree as $item) {
1182 if ($item[$field] == $search) {
1185 if (!empty($item['children'])) {
1186 $found = self
::findInTree($search, $item['children']);