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(&$params, $key) {
65 if (!is_array($params)) {
68 elseif ($value = CRM_Utils_Array
::value($key, $params)) {
72 foreach ($params as $subParam) {
73 if (is_array($subParam) &&
74 $value = self
::retrieveValueRecursive($subParam, $key)
84 * Wraps and slightly changes the behavior of PHP's array_search().
86 * This function reproduces the behavior of array_search() from PHP prior to
87 * version 4.2.0, which was to return NULL on failure. This function also
88 * checks that $list is an array before attempting to search it.
92 * The value to search for.
94 * The array to be searched.
96 * @return int|string|null
97 * Returns the key, which could be an int or a string, or NULL on failure.
99 public static function key($value, $list) {
100 if (is_array($list)) {
101 $key = array_search($value, $list);
103 // array_search returns key if found, false otherwise
104 // it may return values like 0 or empty string which
105 // evaluates to false
106 // hence we must use identical comparison operator
107 return ($key === FALSE) ?
NULL : $key;
113 * Builds an XML fragment representing an array.
115 * Depending on the nature of the keys of the array (and its sub-arrays,
116 * if any) the XML fragment may not be valid.
119 * The array to be serialized.
121 * (optional) Indentation depth counter.
122 * @param string $seperator
123 * (optional) String to be appended after open/close tags.
126 * XML fragment representing $list.
128 public static function &xml(&$list, $depth = 1, $seperator = "\n") {
130 foreach ($list as $name => $value) {
131 $xml .= str_repeat(' ', $depth * 4);
132 if (is_array($value)) {
133 $xml .= "<{$name}>{$seperator}";
134 $xml .= self
::xml($value, $depth +
1, $seperator);
135 $xml .= str_repeat(' ', $depth * 4);
136 $xml .= "</{$name}>{$seperator}";
139 // make sure we escape value
140 $value = self
::escapeXML($value);
141 $xml .= "<{$name}>$value</{$name}>{$seperator}";
148 * Sanitizes a string for serialization in CRM_Utils_Array::xml().
150 * Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A'
153 * @param string $value
154 * String to be sanitized.
157 * Sanitized version of $value.
159 public static function escapeXML($value) {
164 $src = ['&', '<', '>', '\ 1'];
165 $dst = ['&', '<', '>', ','];
168 return str_replace($src, $dst, $value);
172 * Converts a nested array to a flat array.
174 * The nested structure is preserved in the string values of the keys of the
177 * Example nested array:
202 * Corresponding flattened array:
208 * [asdf.merp] => bleep
209 * [asdf.quack.0] => 1
210 * [asdf.quack.1] => 2
211 * [asdf.quack.2] => 3
216 * Array to be flattened.
219 * @param string $prefix
220 * (optional) String to prepend to keys.
221 * @param string $seperator
222 * (optional) String that separates the concatenated keys.
224 public static function flatten(&$list, &$flat, $prefix = '', $seperator = ".") {
225 foreach ($list as $name => $value) {
226 $newPrefix = ($prefix) ?
$prefix . $seperator . $name : $name;
227 if (is_array($value)) {
228 self
::flatten($value, $flat, $newPrefix, $seperator);
231 $flat[$newPrefix] = $value;
237 * Converts an array with path-like keys into a tree of arrays.
239 * This function is the inverse of CRM_Utils_Array::flatten().
241 * @param string $delim
244 * A one-dimensional array indexed by string keys
249 public function unflatten($delim, &$arr) {
251 foreach ($arr as $key => $value) {
252 $path = explode($delim, $key);
254 while (count($path) > 1) {
255 $key = array_shift($path);
256 if (!isset($node[$key])) {
259 $node = &$node[$key];
262 $key = array_shift($path);
263 $node[$key] = $value;
271 * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge
272 * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both
273 * exist but they are not both arrays, the value from $a1 overrides the
274 * value from $a2 and the value from $a2 is discarded.
277 * First array to be merged.
279 * Second array to be merged.
284 public static function crmArrayMerge($a1, $a2) {
294 foreach ($a1 as $key => $value) {
295 if (array_key_exists($key, $a2) &&
296 is_array($a2[$key]) && is_array($a1[$key])
298 $a3[$key] = array_merge($a1[$key], $a2[$key]);
301 $a3[$key] = $a1[$key];
305 foreach ($a2 as $key => $value) {
306 if (array_key_exists($key, $a1)) {
307 // already handled in above loop
310 $a3[$key] = $a2[$key];
317 * Determines whether an array contains any sub-arrays.
320 * The array to inspect.
323 * True if $list contains at least one sub-array, false otherwise.
325 public static function isHierarchical(&$list) {
326 foreach ($list as $n => $v) {
335 * Is array A a subset of array B.
337 * @param array $subset
338 * @param array $superset
341 * TRUE if $subset is a subset of $superset
343 public static function isSubset($subset, $superset) {
344 foreach ($subset as $expected) {
345 if (!in_array($expected, $superset)) {
353 * Searches an array recursively in an optionally case-insensitive manner.
355 * @param string $value
356 * Value to search for.
357 * @param array $params
358 * Array to search within.
359 * @param bool $caseInsensitive
360 * (optional) Whether to search in a case-insensitive manner.
363 * True if $value was found, false otherwise.
365 public static function crmInArray($value, $params, $caseInsensitive = TRUE) {
366 foreach ($params as $item) {
367 if (is_array($item)) {
368 $ret = self
::crmInArray($value, $item, $caseInsensitive);
371 $ret = ($caseInsensitive) ?
strtolower($item) == strtolower($value) : $item == $value;
381 * Convert associative array names to values and vice-versa.
383 * This function is used by by import functions and some webforms.
385 * @param array $defaults
386 * @param string $property
392 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
393 $id = $property . '_id';
395 $src = $reverse ?
$property : $id;
396 $dst = $reverse ?
$id : $property;
398 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER
))) {
402 $look = $reverse ?
array_flip($lookup) : $lookup;
404 // trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
406 foreach ($look as $k => $v) {
407 $newLook[trim($k, ".")] = $v;
412 if (is_array($look)) {
413 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER
))) {
418 $tempLook = array_change_key_case($look, CASE_LOWER
);
420 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
425 * Checks whether an array is empty.
427 * An array is empty if its values consist only of NULL and empty sub-arrays.
428 * Containing a non-NULL value or non-empty array makes an array non-empty.
430 * If something other than an array is passed, it is considered to be empty.
432 * If nothing is passed at all, the default value provided is empty.
434 * @param array $array
435 * (optional) Array to be checked for emptiness.
438 * True if the array is empty.
440 public static function crmIsEmptyArray($array = []) {
441 if (!is_array($array)) {
444 foreach ($array as $element) {
445 if (is_array($element)) {
446 if (!self
::crmIsEmptyArray($element)) {
450 elseif (isset($element)) {
458 * Sorts an associative array of arrays by an attribute using strnatcmp().
460 * @param array $array
461 * Array to be sorted.
462 * @param string|array $field
463 * Name of the attribute used for sorting.
468 public static function crmArraySortByField($array, $field) {
469 $fields = (array) $field;
470 uasort($array, function ($a, $b) use ($fields) {
471 foreach ($fields as $f) {
472 $v = strnatcmp($a[$f], $b[$f]);
483 * Recursively removes duplicate values from a multi-dimensional array.
485 * @param array $array
486 * The input array possibly containing duplicate values.
489 * The input array with duplicate values removed.
491 public static function crmArrayUnique($array) {
492 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
493 foreach ($result as $key => $value) {
494 if (is_array($value)) {
495 $result[$key] = self
::crmArrayUnique($value);
502 * Sorts an array and maintains index association (with localization).
504 * Uses Collate from the PECL "intl" package, if available, for UTF-8
505 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
507 * On Debian/Ubuntu: apt-get install php5-intl
509 * @param array $array
510 * (optional) Array to be sorted.
515 public static function asort($array = []) {
516 $lcMessages = CRM_Utils_System
::getUFLocale();
518 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
519 $collator = new Collator($lcMessages . '.utf8');
520 $collator->asort($array);
523 // This calls PHP's built-in asort().
531 * Unsets an arbitrary list of array elements from an associative array.
533 * @param array $items
534 * The array from which to remove items.
537 * When passed a string, unsets $items[$key].
538 * When passed an array of strings, unsets $items[$k] for each string $k in the array.
540 public static function remove(&$items) {
541 foreach (func_get_args() as $n => $key) {
542 // Skip argument 0 ($items) by testing $n for truth.
543 if ($n && is_array($key)) {
544 foreach ($key as $k) {
555 * Builds an array-tree which indexes the records in an array.
557 * @param string[] $keys
558 * Properties by which to index.
559 * @param object|array $records
562 * Multi-dimensional array, with one layer for each key.
564 public static function index($keys, $records) {
565 $final_key = array_pop($keys);
568 foreach ($records as $record) {
570 foreach ($keys as $key) {
571 if (is_array($record)) {
572 $keyvalue = $record[$key] ??
NULL;
575 $keyvalue = $record->{$key} ??
NULL;
577 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
578 $node[$keyvalue] = [];
580 $node = &$node[$keyvalue];
582 if (is_array($record)) {
583 $node[$record[$final_key]] = $record;
586 $node[$record->{$final_key}] = $record;
593 * Iterates over a list of records and returns the value of some property.
595 * @param string $prop
596 * Property to retrieve.
597 * @param array|object $records
601 * Keys are the original keys of $records; values are the $prop values.
603 public static function collect($prop, $records) {
605 if (is_array($records)) {
606 foreach ($records as $key => $record) {
607 if (is_object($record)) {
608 $result[$key] = $record->{$prop};
611 $result[$key] = self
::value($prop, $record);
619 * Iterates over a list of objects and executes some method on each.
622 * - This is like array_map(), except it executes the objects' method
623 * instead of a free-form callable.
624 * - This is like Array::collect(), except it uses a method
625 * instead of a property.
627 * @param string $method
628 * The method to execute.
629 * @param array|Traversable $objects
632 * An optional list of arguments to pass to the method.
635 * Keys are the original keys of $objects; values are the method results.
637 public static function collectMethod($method, $objects, $args = []) {
639 if (is_array($objects)) {
640 foreach ($objects as $key => $object) {
641 $result[$key] = call_user_func_array([$object, $method], $args);
648 * Trims delimiters from a string and then splits it using explode().
650 * This method works mostly like PHP's built-in explode(), except that
651 * surrounding delimiters are trimmed before explode() is called.
653 * Also, if an array or NULL is passed as the $values parameter, the value is
654 * returned unmodified rather than being passed to explode().
656 * @param array|null|string $values
657 * The input string (or an array, or NULL).
658 * @param string $delim
659 * (optional) The boundary string.
662 * An array of strings produced by explode(), or the unmodified input
665 public static function explodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
666 if ($values === NULL) {
669 // If we already have an array, no need to continue
670 if (is_array($values)) {
673 // Empty string -> empty array
674 if ($values === '') {
677 return explode($delim, trim((string) $values, $delim));
681 * Joins array elements with a string, adding surrounding delimiters.
683 * This method works mostly like PHP's built-in implode(), but the generated
684 * string is surrounded by delimiter characters. Also, if NULL is passed as
685 * the $values parameter, NULL is returned.
687 * @param mixed $values
688 * Array to be imploded. If a non-array is passed, it will be cast to an
690 * @param string $delim
691 * Delimiter to be used for implode() and which will surround the output
694 * @return string|NULL
695 * The generated string, or NULL if NULL was passed as $values parameter.
697 public static function implodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
698 if ($values === NULL) {
701 // If we already have a string, strip $delim off the ends so it doesn't get added twice
702 if (is_string($values)) {
703 $values = trim($values, $delim);
705 return $delim . implode($delim, (array) $values) . $delim;
709 * Modifies a key in an array while preserving the key order.
711 * By default when an element is added to an array, it is added to the end.
712 * This method allows for changing an existing key while preserving its
713 * position in the array.
715 * The array is both modified in-place and returned.
717 * @param array $elementArray
718 * Array to manipulate.
719 * @param string $oldKey
720 * Old key to be replaced.
721 * @param string $newKey
722 * Replacement key string.
725 * Throws a generic Exception if $oldKey is not found in $elementArray.
728 * The manipulated array.
730 public static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
731 $keys = array_keys($elementArray);
732 if (FALSE === $index = array_search($oldKey, $keys)) {
733 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
735 $keys[$index] = $newKey;
736 $elementArray = array_combine($keys, array_values($elementArray));
737 return $elementArray;
741 * Searches array keys by regex, returning the value of the first match.
743 * Given a regular expression and an array, this method searches the keys
744 * of the array using the regular expression. The first match is then used
745 * to index into the array, and the associated value is retrieved and
746 * returned. If no matches are found, or if something other than an array
747 * is passed, then a default value is returned. Unless otherwise specified,
748 * the default value is NULL.
750 * @param string $regexKey
751 * The regular expression to use when searching for matching keys.
753 * The array whose keys will be searched.
754 * @param mixed $default
755 * (optional) The default value to return if the regex does not match an
756 * array key, or if something other than an array is passed.
761 public static function valueByRegexKey($regexKey, $list, $default = NULL) {
762 if (is_array($list) && $regexKey) {
763 $matches = preg_grep($regexKey, array_keys($list));
764 $key = reset($matches);
765 return ($key && array_key_exists($key, $list)) ?
$list[$key] : $default;
771 * Generates the Cartesian product of zero or more vectors.
773 * @param array $dimensions
774 * List of dimensions to multiply.
775 * Each key is a dimension name; each value is a vector.
776 * @param array $template
777 * (optional) A base set of values included in every output.
780 * Each item is a distinct combination of values from $dimensions.
782 * For example, the product of
785 * bg => {white, black}
789 * {fg => red, bg => white},
790 * {fg => red, bg => black},
791 * {fg => blue, bg => white},
792 * {fg => blue, bg => black}
795 public static function product($dimensions, $template = []) {
796 if (empty($dimensions)) {
800 foreach ($dimensions as $key => $value) {
802 $firstValues = $value;
805 unset($dimensions[$key]);
808 foreach ($firstValues as $firstValue) {
809 foreach (self
::product($dimensions, $template) as $result) {
810 $result[$firstKey] = $firstValue;
811 $results[] = $result;
819 * Get the first element of an array.
821 * @param array $array
824 public static function first($array) {
825 foreach ($array as $value) {
832 * Extract any $keys from $array and copy to a new array.
834 * Note: If a $key does not appear in $array, then it will
835 * not appear in the result.
837 * @param array $array
839 * List of keys to copy.
842 public static function subset($array, $keys) {
844 foreach ($keys as $key) {
845 if (isset($array[$key])) {
846 $result[$key] = $array[$key];
853 * Transform an associative array of key=>value pairs into a non-associative array of arrays.
854 * This is necessary to preserve sort order when sending an array through json_encode.
856 * @param array $associative
857 * Ex: ['foo' => 'bar'].
858 * @param string $keyName
860 * @param string $valueName
863 * Ex: [0 => ['key' => 'foo', 'value' => 'bar']].
865 public static function makeNonAssociative($associative, $keyName = 'key', $valueName = 'value') {
867 foreach ($associative as $key => $val) {
868 $output[] = [$keyName => $key, $valueName => $val];
874 * Diff multidimensional arrays
875 * (array_diff does not support multidimensional array)
877 * @param array $array1
878 * @param array $array2
881 public static function multiArrayDiff($array1, $array2) {
883 foreach ($array1 as $mKey => $mValue) {
884 if (array_key_exists($mKey, $array2)) {
885 if (is_array($mValue)) {
886 $recursiveDiff = self
::multiArrayDiff($mValue, $array2[$mKey]);
887 if (count($recursiveDiff)) {
888 $arrayDiff[$mKey] = $recursiveDiff;
892 if ($mValue != $array2[$mKey]) {
893 $arrayDiff[$mKey] = $mValue;
898 $arrayDiff[$mKey] = $mValue;
905 * Given a 2-dimensional matrix, create a new matrix with a restricted list of columns.
907 * @param array $matrix
908 * All matrix data, as a list of rows.
909 * @param array $columns
910 * List of column names.
913 public static function filterColumns($matrix, $columns) {
915 foreach ($matrix as $pos => $oldRow) {
917 foreach ($columns as $column) {
918 $newRow[$column] = $oldRow[$column] ??
NULL;
920 $newRows[$pos] = $newRow;
926 * Rewrite the keys in an array.
928 * @param array $array
929 * @param string|callable $indexBy
930 * Either the value to key by, or a function($key, $value) that returns the new key.
933 public static function rekey($array, $indexBy) {
935 foreach ($array as $key => $value) {
936 $newKey = is_callable($indexBy) ?
$indexBy($key, $value) : $value[$indexBy];
937 $result[$newKey] = $value;
943 * Copy all properties of $other into $array (recursively).
945 * @param array|ArrayAccess $array
946 * @param array $other
948 public static function extend(&$array, $other) {
949 foreach ($other as $key => $value) {
950 if (is_array($value)) {
951 self
::extend($array[$key], $value);
954 $array[$key] = $value;
960 * Get a single value from an array-tree.
962 * @param array $values
963 * Ex: ['foo' => ['bar' => 123]].
965 * Ex: ['foo', 'bar'].
966 * @param mixed $default
970 public static function pathGet($values, $path, $default = NULL) {
971 foreach ($path as $key) {
972 if (!is_array($values) ||
!isset($values[$key])) {
975 $values = $values[$key];
981 * Check if a key isset which may be several layers deep.
983 * This is a helper for when the calling function does not know how many layers deep
984 * the path array is so cannot easily check.
986 * @param array $values
990 public static function pathIsset($values, $path) {
991 foreach ($path as $key) {
992 if (!is_array($values) ||
!isset($values[$key])) {
995 $values = $values[$key];
1001 * Set a single value in an array tree.
1003 * @param array $values
1004 * Ex: ['foo' => ['bar' => 123]].
1005 * @param array $pathParts
1006 * Ex: ['foo', 'bar'].
1010 public static function pathSet(&$values, $pathParts, $value) {
1012 $last = array_pop($pathParts);
1013 foreach ($pathParts as $part) {
1014 if (!isset($r[$part])) {
1023 * Convert a simple dictionary into separate key+value records.
1025 * @param array $array
1026 * Ex: array('foo' => 'bar').
1027 * @param string $keyField
1029 * @param string $valueField
1034 public static function toKeyValueRows($array, $keyField = 'key', $valueField = 'value') {
1035 return self
::makeNonAssociative($array, $keyField, $valueField);
1039 * Convert array where key(s) holds the actual value and value(s) as 1 into array of actual values
1040 * Ex: array('foobar' => 1, 4 => 1) formatted into array('foobar', 4)
1042 * @deprecated use convertCheckboxInputToArray instead (after testing)
1043 * https://github.com/civicrm/civicrm-core/pull/8169
1045 * @param array $array
1047 public static function formatArrayKeys(&$array) {
1048 if (!is_array($array)) {
1051 $keys = array_keys($array, 1);
1052 if (count($keys) > 1 ||
1053 (count($keys) == 1 &&
1054 (current($keys) > 1 ||
1055 is_string(current($keys)) ||
1056 // handle (0 => 4), (1 => 1)
1057 (current($keys) == 1 && $array[1] == 1)
1066 * Convert the data format coming in from checkboxes to an array of values.
1068 * The input format from check boxes looks like
1069 * array('value1' => 1, 'value2' => 1). This function converts those values to
1070 * array(''value1', 'value2).
1072 * The function will only alter the array if all values are equal to 1.
1074 * @param array $input
1078 public static function convertCheckboxFormatToArray($input) {
1079 if (isset($input[0])) {
1082 $keys = array_keys($input, 1);
1083 if ((count($keys) == count($input))) {
1090 * Ensure that array is encoded in utf8 format.
1092 * @param array $array
1094 * @return array $array utf8-encoded.
1096 public static function encode_items($array) {
1097 foreach ($array as $key => $value) {
1098 if (is_array($value)) {
1099 $array[$key] = self
::encode_items($value);
1101 elseif (is_string($value)) {
1102 $array[$key] = mb_convert_encoding($value, mb_detect_encoding($value, mb_detect_order(), TRUE), 'UTF-8');
1105 $array[$key] = $value;
1112 * Build tree of elements.
1114 * @param array $elements
1115 * @param int|null $parentId
1119 public static function buildTree($elements, $parentId = NULL) {
1122 foreach ($elements as $element) {
1123 if ($element['parent_id'] == $parentId) {
1124 $children = self
::buildTree($elements, $element['id']);
1126 $element['children'] = $children;
1128 $branch[] = $element;
1136 * Find search string in tree.
1138 * @param string $search
1139 * @param array $tree
1140 * @param string $field
1142 * @return array|null
1144 public static function findInTree($search, $tree, $field = 'id') {
1145 foreach ($tree as $item) {
1146 if ($item[$field] == $search) {
1149 if (!empty($item['children'])) {
1150 $found = self
::findInTree($search, $item['children']);