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
28 * Key value to look up in the array.
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;
45 * Recursively searches an array for a key, returning the first value found.
47 * If $params[$key] does not exist and $params contains arrays, descend into
48 * each array in a depth-first manner, in array iteration order.
50 * @param array $params
51 * The array to be searched.
53 * The key to search for.
56 * The value of the key, or null if the key is not found.
58 public static function retrieveValueRecursive(&$params, $key) {
59 if (!is_array($params)) {
62 elseif ($value = CRM_Utils_Array
::value($key, $params)) {
66 foreach ($params as $subParam) {
67 if (is_array($subParam) &&
68 $value = self
::retrieveValueRecursive($subParam, $key)
78 * Wraps and slightly changes the behavior of PHP's array_search().
80 * This function reproduces the behavior of array_search() from PHP prior to
81 * version 4.2.0, which was to return NULL on failure. This function also
82 * checks that $list is an array before attempting to search it.
86 * The value to search for.
88 * The array to be searched.
90 * @return int|string|null
91 * Returns the key, which could be an int or a string, or NULL on failure.
93 public static function key($value, $list) {
94 if (is_array($list)) {
95 $key = array_search($value, $list);
97 // array_search returns key if found, false otherwise
98 // it may return values like 0 or empty string which
100 // hence we must use identical comparison operator
101 return ($key === FALSE) ?
NULL : $key;
107 * Builds an XML fragment representing an array.
109 * Depending on the nature of the keys of the array (and its sub-arrays,
110 * if any) the XML fragment may not be valid.
113 * The array to be serialized.
115 * (optional) Indentation depth counter.
116 * @param string $seperator
117 * (optional) String to be appended after open/close tags.
120 * XML fragment representing $list.
122 public static function &xml(&$list, $depth = 1, $seperator = "\n") {
124 foreach ($list as $name => $value) {
125 $xml .= str_repeat(' ', $depth * 4);
126 if (is_array($value)) {
127 $xml .= "<{$name}>{$seperator}";
128 $xml .= self
::xml($value, $depth +
1, $seperator);
129 $xml .= str_repeat(' ', $depth * 4);
130 $xml .= "</{$name}>{$seperator}";
133 // make sure we escape value
134 $value = self
::escapeXML($value);
135 $xml .= "<{$name}>$value</{$name}>{$seperator}";
142 * Sanitizes a string for serialization in CRM_Utils_Array::xml().
144 * Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A'
147 * @param string $value
148 * String to be sanitized.
151 * Sanitized version of $value.
153 public static function escapeXML($value) {
158 $src = ['&', '<', '>', '\ 1'];
159 $dst = ['&', '<', '>', ','];
162 return str_replace($src, $dst, $value);
166 * Converts a nested array to a flat array.
168 * The nested structure is preserved in the string values of the keys of the
171 * Example nested array:
196 * Corresponding flattened array:
202 * [asdf.merp] => bleep
203 * [asdf.quack.0] => 1
204 * [asdf.quack.1] => 2
205 * [asdf.quack.2] => 3
210 * Array to be flattened.
213 * @param string $prefix
214 * (optional) String to prepend to keys.
215 * @param string $seperator
216 * (optional) String that separates the concatenated keys.
218 public static function flatten(&$list, &$flat, $prefix = '', $seperator = ".") {
219 foreach ($list as $name => $value) {
220 $newPrefix = ($prefix) ?
$prefix . $seperator . $name : $name;
221 if (is_array($value)) {
222 self
::flatten($value, $flat, $newPrefix, $seperator);
225 $flat[$newPrefix] = $value;
231 * Converts an array with path-like keys into a tree of arrays.
233 * This function is the inverse of CRM_Utils_Array::flatten().
235 * @param string $delim
238 * A one-dimensional array indexed by string keys
243 public function unflatten($delim, &$arr) {
245 foreach ($arr as $key => $value) {
246 $path = explode($delim, $key);
248 while (count($path) > 1) {
249 $key = array_shift($path);
250 if (!isset($node[$key])) {
253 $node = &$node[$key];
256 $key = array_shift($path);
257 $node[$key] = $value;
265 * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge
266 * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both
267 * exist but they are not both arrays, the value from $a1 overrides the
268 * value from $a2 and the value from $a2 is discarded.
271 * First array to be merged.
273 * Second array to be merged.
278 public static function crmArrayMerge($a1, $a2) {
288 foreach ($a1 as $key => $value) {
289 if (array_key_exists($key, $a2) &&
290 is_array($a2[$key]) && is_array($a1[$key])
292 $a3[$key] = array_merge($a1[$key], $a2[$key]);
295 $a3[$key] = $a1[$key];
299 foreach ($a2 as $key => $value) {
300 if (array_key_exists($key, $a1)) {
301 // already handled in above loop
304 $a3[$key] = $a2[$key];
311 * Determines whether an array contains any sub-arrays.
314 * The array to inspect.
317 * True if $list contains at least one sub-array, false otherwise.
319 public static function isHierarchical(&$list) {
320 foreach ($list as $n => $v) {
329 * Is array A a subset of array B.
331 * @param array $subset
332 * @param array $superset
335 * TRUE if $subset is a subset of $superset
337 public static function isSubset($subset, $superset) {
338 foreach ($subset as $expected) {
339 if (!in_array($expected, $superset)) {
347 * Searches an array recursively in an optionally case-insensitive manner.
349 * @param string $value
350 * Value to search for.
351 * @param array $params
352 * Array to search within.
353 * @param bool $caseInsensitive
354 * (optional) Whether to search in a case-insensitive manner.
357 * True if $value was found, false otherwise.
359 public static function crmInArray($value, $params, $caseInsensitive = TRUE) {
360 foreach ($params as $item) {
361 if (is_array($item)) {
362 $ret = self
::crmInArray($value, $item, $caseInsensitive);
365 $ret = ($caseInsensitive) ?
strtolower($item) == strtolower($value) : $item == $value;
375 * Convert associative array names to values and vice-versa.
377 * This function is used by by import functions and some webforms.
379 * @param array $defaults
380 * @param string $property
386 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
387 $id = $property . '_id';
389 $src = $reverse ?
$property : $id;
390 $dst = $reverse ?
$id : $property;
392 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER
))) {
396 $look = $reverse ?
array_flip($lookup) : $lookup;
398 // trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
400 foreach ($look as $k => $v) {
401 $newLook[trim($k, ".")] = $v;
406 if (is_array($look)) {
407 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER
))) {
412 $tempLook = array_change_key_case($look, CASE_LOWER
);
414 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
419 * Checks whether an array is empty.
421 * An array is empty if its values consist only of NULL and empty sub-arrays.
422 * Containing a non-NULL value or non-empty array makes an array non-empty.
424 * If something other than an array is passed, it is considered to be empty.
426 * If nothing is passed at all, the default value provided is empty.
428 * @param array $array
429 * (optional) Array to be checked for emptiness.
432 * True if the array is empty.
434 public static function crmIsEmptyArray($array = []) {
435 if (!is_array($array)) {
438 foreach ($array as $element) {
439 if (is_array($element)) {
440 if (!self
::crmIsEmptyArray($element)) {
444 elseif (isset($element)) {
452 * Sorts an associative array of arrays by an attribute using strnatcmp().
454 * @param array $array
455 * Array to be sorted.
456 * @param string|array $field
457 * Name of the attribute used for sorting.
462 public static function crmArraySortByField($array, $field) {
463 $fields = (array) $field;
464 uasort($array, function ($a, $b) use ($fields) {
465 foreach ($fields as $f) {
466 $v = strnatcmp($a[$f], $b[$f]);
477 * Recursively removes duplicate values from a multi-dimensional array.
479 * @param array $array
480 * The input array possibly containing duplicate values.
483 * The input array with duplicate values removed.
485 public static function crmArrayUnique($array) {
486 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
487 foreach ($result as $key => $value) {
488 if (is_array($value)) {
489 $result[$key] = self
::crmArrayUnique($value);
496 * Sorts an array and maintains index association (with localization).
498 * Uses Collate from the PECL "intl" package, if available, for UTF-8
499 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
501 * On Debian/Ubuntu: apt-get install php5-intl
503 * @param array $array
504 * (optional) Array to be sorted.
509 public static function asort($array = []) {
510 $lcMessages = CRM_Utils_System
::getUFLocale();
512 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
513 $collator = new Collator($lcMessages . '.utf8');
514 $collator->asort($array);
517 // This calls PHP's built-in asort().
525 * Unsets an arbitrary list of array elements from an associative array.
527 * @param array $items
528 * The array from which to remove items.
531 * When passed a string, unsets $items[$key].
532 * When passed an array of strings, unsets $items[$k] for each string $k in the array.
534 public static function remove(&$items) {
535 foreach (func_get_args() as $n => $key) {
536 // Skip argument 0 ($items) by testing $n for truth.
537 if ($n && is_array($key)) {
538 foreach ($key as $k) {
549 * Builds an array-tree which indexes the records in an array.
551 * @param string[] $keys
552 * Properties by which to index.
553 * @param object|array $records
556 * Multi-dimensional array, with one layer for each key.
558 public static function index($keys, $records) {
559 $final_key = array_pop($keys);
562 foreach ($records as $record) {
564 foreach ($keys as $key) {
565 if (is_array($record)) {
566 $keyvalue = isset($record[$key]) ?
$record[$key] : NULL;
569 $keyvalue = isset($record->{$key}) ?
$record->{$key} : NULL;
571 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
572 $node[$keyvalue] = [];
574 $node = &$node[$keyvalue];
576 if (is_array($record)) {
577 $node[$record[$final_key]] = $record;
580 $node[$record->{$final_key}] = $record;
587 * Iterates over a list of records and returns the value of some property.
589 * @param string $prop
590 * Property to retrieve.
591 * @param array|object $records
595 * Keys are the original keys of $records; values are the $prop values.
597 public static function collect($prop, $records) {
599 if (is_array($records)) {
600 foreach ($records as $key => $record) {
601 if (is_object($record)) {
602 $result[$key] = $record->{$prop};
605 $result[$key] = self
::value($prop, $record);
613 * Iterates over a list of objects and executes some method on each.
616 * - This is like array_map(), except it executes the objects' method
617 * instead of a free-form callable.
618 * - This is like Array::collect(), except it uses a method
619 * instead of a property.
621 * @param string $method
622 * The method to execute.
623 * @param array|Traversable $objects
626 * An optional list of arguments to pass to the method.
629 * Keys are the original keys of $objects; values are the method results.
631 public static function collectMethod($method, $objects, $args = []) {
633 if (is_array($objects)) {
634 foreach ($objects as $key => $object) {
635 $result[$key] = call_user_func_array([$object, $method], $args);
642 * Trims delimiters from a string and then splits it using explode().
644 * This method works mostly like PHP's built-in explode(), except that
645 * surrounding delimiters are trimmed before explode() is called.
647 * Also, if an array or NULL is passed as the $values parameter, the value is
648 * returned unmodified rather than being passed to explode().
650 * @param array|null|string $values
651 * The input string (or an array, or NULL).
652 * @param string $delim
653 * (optional) The boundary string.
656 * An array of strings produced by explode(), or the unmodified input
659 public static function explodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
660 if ($values === NULL) {
663 // If we already have an array, no need to continue
664 if (is_array($values)) {
667 // Empty string -> empty array
668 if ($values === '') {
671 return explode($delim, trim((string) $values, $delim));
675 * Joins array elements with a string, adding surrounding delimiters.
677 * This method works mostly like PHP's built-in implode(), but the generated
678 * string is surrounded by delimiter characters. Also, if NULL is passed as
679 * the $values parameter, NULL is returned.
681 * @param mixed $values
682 * Array to be imploded. If a non-array is passed, it will be cast to an
684 * @param string $delim
685 * Delimiter to be used for implode() and which will surround the output
688 * @return string|NULL
689 * The generated string, or NULL if NULL was passed as $values parameter.
691 public static function implodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
692 if ($values === NULL) {
695 // If we already have a string, strip $delim off the ends so it doesn't get added twice
696 if (is_string($values)) {
697 $values = trim($values, $delim);
699 return $delim . implode($delim, (array) $values) . $delim;
703 * Modifies a key in an array while preserving the key order.
705 * By default when an element is added to an array, it is added to the end.
706 * This method allows for changing an existing key while preserving its
707 * position in the array.
709 * The array is both modified in-place and returned.
711 * @param array $elementArray
712 * Array to manipulate.
713 * @param string $oldKey
714 * Old key to be replaced.
715 * @param string $newKey
716 * Replacement key string.
719 * Throws a generic Exception if $oldKey is not found in $elementArray.
722 * The manipulated array.
724 public static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
725 $keys = array_keys($elementArray);
726 if (FALSE === $index = array_search($oldKey, $keys)) {
727 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
729 $keys[$index] = $newKey;
730 $elementArray = array_combine($keys, array_values($elementArray));
731 return $elementArray;
735 * Searches array keys by regex, returning the value of the first match.
737 * Given a regular expression and an array, this method searches the keys
738 * of the array using the regular expression. The first match is then used
739 * to index into the array, and the associated value is retrieved and
740 * returned. If no matches are found, or if something other than an array
741 * is passed, then a default value is returned. Unless otherwise specified,
742 * the default value is NULL.
744 * @param string $regexKey
745 * The regular expression to use when searching for matching keys.
747 * The array whose keys will be searched.
748 * @param mixed $default
749 * (optional) The default value to return if the regex does not match an
750 * array key, or if something other than an array is passed.
755 public static function valueByRegexKey($regexKey, $list, $default = NULL) {
756 if (is_array($list) && $regexKey) {
757 $matches = preg_grep($regexKey, array_keys($list));
758 $key = reset($matches);
759 return ($key && array_key_exists($key, $list)) ?
$list[$key] : $default;
765 * Generates the Cartesian product of zero or more vectors.
767 * @param array $dimensions
768 * List of dimensions to multiply.
769 * Each key is a dimension name; each value is a vector.
770 * @param array $template
771 * (optional) A base set of values included in every output.
774 * Each item is a distinct combination of values from $dimensions.
776 * For example, the product of
779 * bg => {white, black}
783 * {fg => red, bg => white},
784 * {fg => red, bg => black},
785 * {fg => blue, bg => white},
786 * {fg => blue, bg => black}
789 public static function product($dimensions, $template = []) {
790 if (empty($dimensions)) {
794 foreach ($dimensions as $key => $value) {
796 $firstValues = $value;
799 unset($dimensions[$key]);
802 foreach ($firstValues as $firstValue) {
803 foreach (self
::product($dimensions, $template) as $result) {
804 $result[$firstKey] = $firstValue;
805 $results[] = $result;
813 * Get the first element of an array.
815 * @param array $array
818 public static function first($array) {
819 foreach ($array as $value) {
826 * Extract any $keys from $array and copy to a new array.
828 * Note: If a $key does not appear in $array, then it will
829 * not appear in the result.
831 * @param array $array
833 * List of keys to copy.
836 public static function subset($array, $keys) {
838 foreach ($keys as $key) {
839 if (isset($array[$key])) {
840 $result[$key] = $array[$key];
847 * Transform an associative array of key=>value pairs into a non-associative array of arrays.
848 * This is necessary to preserve sort order when sending an array through json_encode.
850 * @param array $associative
851 * Ex: ['foo' => 'bar'].
852 * @param string $keyName
854 * @param string $valueName
857 * Ex: [0 => ['key' => 'foo', 'value' => 'bar']].
859 public static function makeNonAssociative($associative, $keyName = 'key', $valueName = 'value') {
861 foreach ($associative as $key => $val) {
862 $output[] = [$keyName => $key, $valueName => $val];
868 * Diff multidimensional arrays
869 * (array_diff does not support multidimensional array)
871 * @param array $array1
872 * @param array $array2
875 public static function multiArrayDiff($array1, $array2) {
877 foreach ($array1 as $mKey => $mValue) {
878 if (array_key_exists($mKey, $array2)) {
879 if (is_array($mValue)) {
880 $recursiveDiff = self
::multiArrayDiff($mValue, $array2[$mKey]);
881 if (count($recursiveDiff)) {
882 $arrayDiff[$mKey] = $recursiveDiff;
886 if ($mValue != $array2[$mKey]) {
887 $arrayDiff[$mKey] = $mValue;
892 $arrayDiff[$mKey] = $mValue;
899 * Given a 2-dimensional matrix, create a new matrix with a restricted list of columns.
901 * @param array $matrix
902 * All matrix data, as a list of rows.
903 * @param array $columns
904 * List of column names.
907 public static function filterColumns($matrix, $columns) {
909 foreach ($matrix as $pos => $oldRow) {
911 foreach ($columns as $column) {
912 $newRow[$column] = CRM_Utils_Array
::value($column, $oldRow);
914 $newRows[$pos] = $newRow;
920 * Rewrite the keys in an array.
922 * @param array $array
923 * @param string|callable $indexBy
924 * Either the value to key by, or a function($key, $value) that returns the new key.
927 public static function rekey($array, $indexBy) {
929 foreach ($array as $key => $value) {
930 $newKey = is_callable($indexBy) ?
$indexBy($key, $value) : $value[$indexBy];
931 $result[$newKey] = $value;
937 * Copy all properties of $other into $array (recursively).
939 * @param array|ArrayAccess $array
940 * @param array $other
942 public static function extend(&$array, $other) {
943 foreach ($other as $key => $value) {
944 if (is_array($value)) {
945 self
::extend($array[$key], $value);
948 $array[$key] = $value;
954 * Get a single value from an array-tree.
956 * @param array $values
957 * Ex: ['foo' => ['bar' => 123]].
959 * Ex: ['foo', 'bar'].
960 * @param mixed $default
964 public static function pathGet($values, $path, $default = NULL) {
965 foreach ($path as $key) {
966 if (!is_array($values) ||
!isset($values[$key])) {
969 $values = $values[$key];
975 * Check if a key isset which may be several layers deep.
977 * This is a helper for when the calling function does not know how many layers deep
978 * the path array is so cannot easily check.
980 * @param array $values
984 public static function pathIsset($values, $path) {
985 foreach ($path as $key) {
986 if (!is_array($values) ||
!isset($values[$key])) {
989 $values = $values[$key];
995 * Set a single value in an array tree.
997 * @param array $values
998 * Ex: ['foo' => ['bar' => 123]].
999 * @param array $pathParts
1000 * Ex: ['foo', 'bar'].
1004 public static function pathSet(&$values, $pathParts, $value) {
1006 $last = array_pop($pathParts);
1007 foreach ($pathParts as $part) {
1008 if (!isset($r[$part])) {
1017 * Convert a simple dictionary into separate key+value records.
1019 * @param array $array
1020 * Ex: array('foo' => 'bar').
1021 * @param string $keyField
1023 * @param string $valueField
1028 public static function toKeyValueRows($array, $keyField = 'key', $valueField = 'value') {
1029 return self
::makeNonAssociative($array, $keyField, $valueField);
1033 * Convert array where key(s) holds the actual value and value(s) as 1 into array of actual values
1034 * Ex: array('foobar' => 1, 4 => 1) formatted into array('foobar', 4)
1036 * @deprecated use convertCheckboxInputToArray instead (after testing)
1037 * https://github.com/civicrm/civicrm-core/pull/8169
1039 * @param array $array
1041 public static function formatArrayKeys(&$array) {
1042 if (!is_array($array)) {
1045 $keys = array_keys($array, 1);
1046 if (count($keys) > 1 ||
1047 (count($keys) == 1 &&
1048 (current($keys) > 1 ||
1049 is_string(current($keys)) ||
1050 // handle (0 => 4), (1 => 1)
1051 (current($keys) == 1 && $array[1] == 1)
1060 * Convert the data format coming in from checkboxes to an array of values.
1062 * The input format from check boxes looks like
1063 * array('value1' => 1, 'value2' => 1). This function converts those values to
1064 * array(''value1', 'value2).
1066 * The function will only alter the array if all values are equal to 1.
1068 * @param array $input
1072 public static function convertCheckboxFormatToArray($input) {
1073 if (isset($input[0])) {
1076 $keys = array_keys($input, 1);
1077 if ((count($keys) == count($input))) {
1084 * Ensure that array is encoded in utf8 format.
1086 * @param array $array
1088 * @return array $array utf8-encoded.
1090 public static function encode_items($array) {
1091 foreach ($array as $key => $value) {
1092 if (is_array($value)) {
1093 $array[$key] = self
::encode_items($value);
1095 elseif (is_string($value)) {
1096 $array[$key] = mb_convert_encoding($value, mb_detect_encoding($value, mb_detect_order(), TRUE), 'UTF-8');
1099 $array[$key] = $value;
1106 * Build tree of elements.
1108 * @param array $elements
1109 * @param int|null $parentId
1113 public static function buildTree($elements, $parentId = NULL) {
1116 foreach ($elements as $element) {
1117 if ($element['parent_id'] == $parentId) {
1118 $children = self
::buildTree($elements, $element['id']);
1120 $element['children'] = $children;
1122 $branch[] = $element;
1130 * Find search string in tree.
1132 * @param string $search
1133 * @param array $tree
1134 * @param string $field
1136 * @return array|null
1138 public static function findInTree($search, $tree, $field = 'id') {
1139 foreach ($tree as $item) {
1140 if ($item[$field] == $search) {
1143 if (!empty($item['children'])) {
1144 $found = self
::findInTree($search, $item['children']);