3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Provides a collection of static methods for array manipulation.
32 * @copyright CiviCRM LLC (c) 2004-2017
34 class CRM_Utils_Array
{
37 * Returns $list[$key] if such element exists, or a default value otherwise.
39 * If $list is not actually an array at all, then the default value is
44 * Key value to look up in the array.
46 * Array from which to look up a value.
47 * @param mixed $default
48 * (optional) Value to return $list[$key] does not exist.
51 * Can return any type, since $list might contain anything.
53 public static function value($key, $list, $default = NULL) {
54 if (is_array($list)) {
55 return array_key_exists($key, $list) ?
$list[$key] : $default;
61 * Recursively searches an array for a key, returning the first value found.
63 * If $params[$key] does not exist and $params contains arrays, descend into
64 * each array in a depth-first manner, in array iteration order.
66 * @param array $params
67 * The array to be searched.
69 * The key to search for.
72 * The value of the key, or null if the key is not found.
74 public static function retrieveValueRecursive(&$params, $key) {
75 if (!is_array($params)) {
78 elseif ($value = CRM_Utils_Array
::value($key, $params)) {
82 foreach ($params as $subParam) {
83 if (is_array($subParam) &&
84 $value = self
::retrieveValueRecursive($subParam, $key)
94 * Wraps and slightly changes the behavior of PHP's array_search().
96 * This function reproduces the behavior of array_search() from PHP prior to
97 * version 4.2.0, which was to return NULL on failure. This function also
98 * checks that $list is an array before attempting to search it.
101 * @param mixed $value
102 * The value to search for.
104 * The array to be searched.
106 * @return int|string|null
107 * Returns the key, which could be an int or a string, or NULL on failure.
109 public static function key($value, $list) {
110 if (is_array($list)) {
111 $key = array_search($value, $list);
113 // array_search returns key if found, false otherwise
114 // it may return values like 0 or empty string which
115 // evaluates to false
116 // hence we must use identical comparison operator
117 return ($key === FALSE) ?
NULL : $key;
123 * Builds an XML fragment representing an array.
125 * Depending on the nature of the keys of the array (and its sub-arrays,
126 * if any) the XML fragment may not be valid.
129 * The array to be serialized.
131 * (optional) Indentation depth counter.
132 * @param string $seperator
133 * (optional) String to be appended after open/close tags.
136 * XML fragment representing $list.
138 public static function &xml(&$list, $depth = 1, $seperator = "\n") {
140 foreach ($list as $name => $value) {
141 $xml .= str_repeat(' ', $depth * 4);
142 if (is_array($value)) {
143 $xml .= "<{$name}>{$seperator}";
144 $xml .= self
::xml($value, $depth +
1, $seperator);
145 $xml .= str_repeat(' ', $depth * 4);
146 $xml .= "</{$name}>{$seperator}";
149 // make sure we escape value
150 $value = self
::escapeXML($value);
151 $xml .= "<{$name}>$value</{$name}>{$seperator}";
158 * Sanitizes a string for serialization in CRM_Utils_Array::xml().
160 * Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A'
163 * @param string $value
164 * String to be sanitized.
167 * Sanitized version of $value.
169 public static function escapeXML($value) {
174 $src = array('&', '<', '>', '\ 1');
175 $dst = array('&', '<', '>', ',');
178 return str_replace($src, $dst, $value);
182 * Converts a nested array to a flat array.
184 * The nested structure is preserved in the string values of the keys of the
187 * Example nested array:
212 * Corresponding flattened array:
218 * [asdf.merp] => bleep
219 * [asdf.quack.0] => 1
220 * [asdf.quack.1] => 2
221 * [asdf.quack.2] => 3
226 * Array to be flattened.
229 * @param string $prefix
230 * (optional) String to prepend to keys.
231 * @param string $seperator
232 * (optional) String that separates the concatenated keys.
234 public static function flatten(&$list, &$flat, $prefix = '', $seperator = ".") {
235 foreach ($list as $name => $value) {
236 $newPrefix = ($prefix) ?
$prefix . $seperator . $name : $name;
237 if (is_array($value)) {
238 self
::flatten($value, $flat, $newPrefix, $seperator);
241 if (!empty($value)) {
242 $flat[$newPrefix] = $value;
249 * Converts an array with path-like keys into a tree of arrays.
251 * This function is the inverse of CRM_Utils_Array::flatten().
253 * @param string $delim
256 * A one-dimensional array indexed by string keys
261 public function unflatten($delim, &$arr) {
263 foreach ($arr as $key => $value) {
264 $path = explode($delim, $key);
266 while (count($path) > 1) {
267 $key = array_shift($path);
268 if (!isset($node[$key])) {
269 $node[$key] = array();
271 $node = &$node[$key];
274 $key = array_shift($path);
275 $node[$key] = $value;
283 * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge
284 * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both
285 * exist but they are not both arrays, the value from $a1 overrides the
286 * value from $a2 and the value from $a2 is discarded.
289 * First array to be merged.
291 * Second array to be merged.
296 public static function crmArrayMerge($a1, $a2) {
306 foreach ($a1 as $key => $value) {
307 if (array_key_exists($key, $a2) &&
308 is_array($a2[$key]) && is_array($a1[$key])
310 $a3[$key] = array_merge($a1[$key], $a2[$key]);
313 $a3[$key] = $a1[$key];
317 foreach ($a2 as $key => $value) {
318 if (array_key_exists($key, $a1)) {
319 // already handled in above loop
322 $a3[$key] = $a2[$key];
329 * Determines whether an array contains any sub-arrays.
332 * The array to inspect.
335 * True if $list contains at least one sub-array, false otherwise.
337 public static function isHierarchical(&$list) {
338 foreach ($list as $n => $v) {
347 * Is array A a subset of array B.
349 * @param array $subset
350 * @param array $superset
353 * TRUE if $subset is a subset of $superset
355 public static function isSubset($subset, $superset) {
356 foreach ($subset as $expected) {
357 if (!in_array($expected, $superset)) {
365 * Searches an array recursively in an optionally case-insensitive manner.
367 * @param string $value
368 * Value to search for.
369 * @param array $params
370 * Array to search within.
371 * @param bool $caseInsensitive
372 * (optional) Whether to search in a case-insensitive manner.
375 * True if $value was found, false otherwise.
377 public static function crmInArray($value, $params, $caseInsensitive = TRUE) {
378 foreach ($params as $item) {
379 if (is_array($item)) {
380 $ret = crmInArray($value, $item, $caseInsensitive);
383 $ret = ($caseInsensitive) ?
strtolower($item) == strtolower($value) : $item == $value;
393 * Convert associative array names to values and vice-versa.
395 * This function is used by both the web form layer and the api. Note that
396 * the api needs the name => value conversion, also the view layer typically
397 * requires value => name conversion
399 * @param array $defaults
400 * @param string $property
406 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
407 $id = $property . '_id';
409 $src = $reverse ?
$property : $id;
410 $dst = $reverse ?
$id : $property;
412 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER
))) {
416 $look = $reverse ?
array_flip($lookup) : $lookup;
418 // trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
420 foreach ($look as $k => $v) {
421 $newLook[trim($k, ".")] = $v;
426 if (is_array($look)) {
427 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER
))) {
432 $tempLook = array_change_key_case($look, CASE_LOWER
);
434 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
439 * Checks whether an array is empty.
441 * An array is empty if its values consist only of NULL and empty sub-arrays.
442 * Containing a non-NULL value or non-empty array makes an array non-empty.
444 * If something other than an array is passed, it is considered to be empty.
446 * If nothing is passed at all, the default value provided is empty.
448 * @param array $array
449 * (optional) Array to be checked for emptiness.
452 * True if the array is empty.
454 public static function crmIsEmptyArray($array = array()) {
455 if (!is_array($array)) {
458 foreach ($array as $element) {
459 if (is_array($element)) {
460 if (!self
::crmIsEmptyArray($element)) {
464 elseif (isset($element)) {
472 * Sorts an associative array of arrays by an attribute using strnatcmp().
474 * @param array $array
475 * Array to be sorted.
476 * @param string|array $field
477 * Name of the attribute used for sorting.
482 public static function crmArraySortByField($array, $field) {
483 $fields = (array) $field;
484 uasort($array, function ($a, $b) use ($fields) {
485 foreach ($fields as $f) {
486 $v = strnatcmp($a[$f], $b[$f]);
497 * Recursively removes duplicate values from a multi-dimensional array.
499 * @param array $array
500 * The input array possibly containing duplicate values.
503 * The input array with duplicate values removed.
505 public static function crmArrayUnique($array) {
506 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
507 foreach ($result as $key => $value) {
508 if (is_array($value)) {
509 $result[$key] = self
::crmArrayUnique($value);
516 * Sorts an array and maintains index association (with localization).
518 * Uses Collate from the PECL "intl" package, if available, for UTF-8
519 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
521 * On Debian/Ubuntu: apt-get install php5-intl
523 * @param array $array
524 * (optional) Array to be sorted.
529 public static function asort($array = array()) {
530 $lcMessages = CRM_Utils_System
::getUFLocale();
532 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
533 $collator = new Collator($lcMessages . '.utf8');
534 $collator->asort($array);
537 // This calls PHP's built-in asort().
545 * Unsets an arbitrary list of array elements from an associative array.
547 * @param array $items
548 * The array from which to remove items.
551 * When passed a string, unsets $items[$key].
552 * When passed an array of strings, unsets $items[$k] for each string $k in the array.
554 public static function remove(&$items) {
555 foreach (func_get_args() as $n => $key) {
556 // Skip argument 0 ($items) by testing $n for truth.
557 if ($n && is_array($key)) {
558 foreach ($key as $k) {
569 * Builds an array-tree which indexes the records in an array.
571 * @param string[] $keys
572 * Properties by which to index.
573 * @param object|array $records
576 * Multi-dimensional array, with one layer for each key.
578 public static function index($keys, $records) {
579 $final_key = array_pop($keys);
582 foreach ($records as $record) {
584 foreach ($keys as $key) {
585 if (is_array($record)) {
586 $keyvalue = isset($record[$key]) ?
$record[$key] : NULL;
589 $keyvalue = isset($record->{$key}) ?
$record->{$key} : NULL;
591 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
592 $node[$keyvalue] = array();
594 $node = &$node[$keyvalue];
596 if (is_array($record)) {
597 $node[$record[$final_key]] = $record;
600 $node[$record->{$final_key}] = $record;
607 * Iterates over a list of records and returns the value of some property.
609 * @param string $prop
610 * Property to retrieve.
611 * @param array|object $records
615 * Keys are the original keys of $records; values are the $prop values.
617 public static function collect($prop, $records) {
619 if (is_array($records)) {
620 foreach ($records as $key => $record) {
621 if (is_object($record)) {
622 $result[$key] = $record->{$prop};
625 $result[$key] = $record[$prop];
633 * Iterates over a list of objects and executes some method on each.
636 * - This is like array_map(), except it executes the objects' method
637 * instead of a free-form callable.
638 * - This is like Array::collect(), except it uses a method
639 * instead of a property.
641 * @param string $method
642 * The method to execute.
643 * @param array|Traversable $objects
646 * An optional list of arguments to pass to the method.
649 * Keys are the original keys of $objects; values are the method results.
651 public static function collectMethod($method, $objects, $args = array()) {
653 if (is_array($objects)) {
654 foreach ($objects as $key => $object) {
655 $result[$key] = call_user_func_array(array($object, $method), $args);
662 * Trims delimiters from a string and then splits it using explode().
664 * This method works mostly like PHP's built-in explode(), except that
665 * surrounding delimiters are trimmed before explode() is called.
667 * Also, if an array or NULL is passed as the $values parameter, the value is
668 * returned unmodified rather than being passed to explode().
670 * @param array|null|string $values
671 * The input string (or an array, or NULL).
672 * @param string $delim
673 * (optional) The boundary string.
676 * An array of strings produced by explode(), or the unmodified input
679 public static function explodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
680 if ($values === NULL) {
683 // If we already have an array, no need to continue
684 if (is_array($values)) {
687 // Empty string -> empty array
688 if ($values === '') {
691 return explode($delim, trim((string) $values, $delim));
695 * Joins array elements with a string, adding surrounding delimiters.
697 * This method works mostly like PHP's built-in implode(), but the generated
698 * string is surrounded by delimiter characters. Also, if NULL is passed as
699 * the $values parameter, NULL is returned.
701 * @param mixed $values
702 * Array to be imploded. If a non-array is passed, it will be cast to an
704 * @param string $delim
705 * Delimiter to be used for implode() and which will surround the output
708 * @return string|NULL
709 * The generated string, or NULL if NULL was passed as $values parameter.
711 public static function implodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
712 if ($values === NULL) {
715 // If we already have a string, strip $delim off the ends so it doesn't get added twice
716 if (is_string($values)) {
717 $values = trim($values, $delim);
719 return $delim . implode($delim, (array) $values) . $delim;
723 * Modifies a key in an array while preserving the key order.
725 * By default when an element is added to an array, it is added to the end.
726 * This method allows for changing an existing key while preserving its
727 * position in the array.
729 * The array is both modified in-place and returned.
731 * @param array $elementArray
732 * Array to manipulate.
733 * @param string $oldKey
734 * Old key to be replaced.
735 * @param string $newKey
736 * Replacement key string.
739 * Throws a generic Exception if $oldKey is not found in $elementArray.
742 * The manipulated array.
744 public static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
745 $keys = array_keys($elementArray);
746 if (FALSE === $index = array_search($oldKey, $keys)) {
747 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
749 $keys[$index] = $newKey;
750 $elementArray = array_combine($keys, array_values($elementArray));
751 return $elementArray;
755 * Searches array keys by regex, returning the value of the first match.
757 * Given a regular expression and an array, this method searches the keys
758 * of the array using the regular expression. The first match is then used
759 * to index into the array, and the associated value is retrieved and
760 * returned. If no matches are found, or if something other than an array
761 * is passed, then a default value is returned. Unless otherwise specified,
762 * the default value is NULL.
764 * @param string $regexKey
765 * The regular expression to use when searching for matching keys.
767 * The array whose keys will be searched.
768 * @param mixed $default
769 * (optional) The default value to return if the regex does not match an
770 * array key, or if something other than an array is passed.
775 public static function valueByRegexKey($regexKey, $list, $default = NULL) {
776 if (is_array($list) && $regexKey) {
777 $matches = preg_grep($regexKey, array_keys($list));
778 $key = reset($matches);
779 return ($key && array_key_exists($key, $list)) ?
$list[$key] : $default;
785 * Generates the Cartesian product of zero or more vectors.
787 * @param array $dimensions
788 * List of dimensions to multiply.
789 * Each key is a dimension name; each value is a vector.
790 * @param array $template
791 * (optional) A base set of values included in every output.
794 * Each item is a distinct combination of values from $dimensions.
796 * For example, the product of
799 * bg => {white, black}
803 * {fg => red, bg => white},
804 * {fg => red, bg => black},
805 * {fg => blue, bg => white},
806 * {fg => blue, bg => black}
809 public static function product($dimensions, $template = array()) {
810 if (empty($dimensions)) {
811 return array($template);
814 foreach ($dimensions as $key => $value) {
816 $firstValues = $value;
819 unset($dimensions[$key]);
822 foreach ($firstValues as $firstValue) {
823 foreach (self
::product($dimensions, $template) as $result) {
824 $result[$firstKey] = $firstValue;
825 $results[] = $result;
833 * Get the first element of an array.
835 * @param array $array
838 public static function first($array) {
839 foreach ($array as $value) {
846 * Extract any $keys from $array and copy to a new array.
848 * Note: If a $key does not appear in $array, then it will
849 * not appear in the result.
851 * @param array $array
853 * List of keys to copy.
856 public static function subset($array, $keys) {
858 foreach ($keys as $key) {
859 if (isset($array[$key])) {
860 $result[$key] = $array[$key];
867 * Transform an associative array of key=>value pairs into a non-associative array of arrays.
868 * This is necessary to preserve sort order when sending an array through json_encode.
870 * @param array $associative
871 * @param string $keyName
872 * @param string $valueName
875 public static function makeNonAssociative($associative, $keyName = 'key', $valueName = 'value') {
877 foreach ($associative as $key => $val) {
878 $output[] = array($keyName => $key, $valueName => $val);
884 * Diff multidimensional arrays
885 * (array_diff does not support multidimensional array)
887 * @param array $array1
888 * @param array $array2
891 public static function multiArrayDiff($array1, $array2) {
892 $arrayDiff = array();
893 foreach ($array1 as $mKey => $mValue) {
894 if (array_key_exists($mKey, $array2)) {
895 if (is_array($mValue)) {
896 $recursiveDiff = self
::multiArrayDiff($mValue, $array2[$mKey]);
897 if (count($recursiveDiff)) {
898 $arrayDiff[$mKey] = $recursiveDiff;
902 if ($mValue != $array2[$mKey]) {
903 $arrayDiff[$mKey] = $mValue;
908 $arrayDiff[$mKey] = $mValue;
915 * Given a 2-dimensional matrix, create a new matrix with a restricted list of columns.
917 * @param array $matrix
918 * All matrix data, as a list of rows.
919 * @param array $columns
920 * List of column names.
923 public static function filterColumns($matrix, $columns) {
925 foreach ($matrix as $pos => $oldRow) {
927 foreach ($columns as $column) {
928 $newRow[$column] = CRM_Utils_Array
::value($column, $oldRow);
930 $newRows[$pos] = $newRow;
936 * Rewrite the keys in an array.
938 * @param array $array
939 * @param string|callable $indexBy
940 * Either the value to key by, or a function($key, $value) that returns the new key.
943 public static function rekey($array, $indexBy) {
945 foreach ($array as $key => $value) {
946 $newKey = is_callable($indexBy) ?
$indexBy($key, $value) : $value[$indexBy];
947 $result[$newKey] = $value;
953 * Copy all properties of $other into $array (recursively).
955 * @param array|ArrayAccess $array
956 * @param array $other
958 public static function extend(&$array, $other) {
959 foreach ($other as $key => $value) {
960 if (is_array($value)) {
961 self
::extend($array[$key], $value);
964 $array[$key] = $value;
970 * Get a single value from an array-tre.
973 * Ex: array('foo'=>array('bar'=>123)).
974 * @param array $pathParts
975 * Ex: array('foo',bar').
979 public static function pathGet($arr, $pathParts) {
981 foreach ($pathParts as $part) {
982 if (!isset($r[$part])) {
991 * Set a single value in an array tree.
994 * Ex: array('foo'=>array('bar'=>123)).
995 * @param array $pathParts
996 * Ex: array('foo',bar').
1000 public static function pathSet(&$arr, $pathParts, $value) {
1002 $last = array_pop($pathParts);
1003 foreach ($pathParts as $part) {
1004 if (!isset($r[$part])) {
1005 $r[$part] = array();
1013 * Convert a simple dictionary into separate key+value records.
1015 * @param array $array
1016 * Ex: array('foo' => 'bar').
1017 * @param string $keyField
1019 * @param string $valueField
1023 * 0 => array('key' => 'foo', 'value' => 'bar')
1026 public static function toKeyValueRows($array, $keyField = 'key', $valueField = 'value') {
1028 foreach ($array as $key => $value) {
1031 $valueField => $value,
1038 * Convert array where key(s) holds the actual value and value(s) as 1 into array of actual values
1039 * Ex: array('foobar' => 1, 4 => 1) formatted into array('foobar', 4)
1041 * @deprecated use convertCheckboxInputToArray instead (after testing)
1042 * https://github.com/civicrm/civicrm-core/pull/8169
1044 * @param array $array
1046 public static function formatArrayKeys(&$array) {
1047 if (!is_array($array)) {
1050 $keys = array_keys($array, 1);
1051 if (count($keys) > 1 ||
1052 (count($keys) == 1 &&
1053 (current($keys) > 1 ||
1054 is_string(current($keys)) ||
1055 (current($keys) == 1 && $array[1] == 1) // handle (0 => 4), (1 => 1)
1064 * Convert the data format coming in from checkboxes to an array of values.
1066 * The input format from check boxes looks like
1067 * array('value1' => 1, 'value2' => 1). This function converts those values to
1068 * array(''value1', 'value2).
1070 * The function will only alter the array if all values are equal to 1.
1072 * @param array $input
1076 public static function convertCheckboxFormatToArray($input) {
1077 if (isset($input[0])) {
1080 $keys = array_keys($input, 1);
1081 if ((count($keys) == count($input))) {
1088 * Ensure that array is encoded in utf8 format.
1090 * @param array $array
1092 * @return array $array utf8-encoded.
1094 public static function encode_items($array) {
1095 foreach ($array as $key => $value) {
1096 if (is_array($value)) {
1097 $array[$key] = self
::encode_items($value);
1099 elseif (is_string($value)) {
1100 $array[$key] = mb_convert_encoding($value, mb_detect_encoding($value, mb_detect_order(), TRUE), 'UTF-8');
1103 $array[$key] = $value;
1110 * Build tree of elements.
1112 * @param array $elements
1113 * @param int|null $parentId
1117 public static function buildTree($elements, $parentId = NULL) {
1120 foreach ($elements as $element) {
1121 if ($element['parent_id'] == $parentId) {
1122 $children = self
::buildTree($elements, $element['id']);
1124 $element['children'] = $children;
1126 $branch[] = $element;
1134 * Find search string in tree.
1136 * @param string $search
1137 * @param array $tree
1138 * @param string $field
1140 * @return array|null
1142 public static function findInTree($search, $tree, $field = 'id') {
1143 foreach ($tree as $item) {
1144 if ($item[$field] == $search) {
1147 if (!empty($item['children'])) {
1148 $found = self
::findInTree($search, $item['children']);