3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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
45 * Key value to look up in the array.
47 * Array from which to look up a value.
48 * @param mixed $default
49 * (optional) Value to return $list[$key] does not exist.
52 * Can return any type, since $list might contain anything.
54 static function value($key, $list, $default = NULL) {
55 if (is_array($list)) {
56 return array_key_exists($key, $list) ?
$list[$key] : $default;
62 * Recursively searches an array for a key, returning the first value found.
64 * If $params[$key] does not exist and $params contains arrays, descend into
65 * each array in a depth-first manner, in array iteration order.
67 * @param array $params
68 * The array to be searched.
70 * The key to search for.
73 * The value of the key, or null if the key is not found.
76 static function retrieveValueRecursive(&$params, $key) {
77 if (!is_array($params)) {
80 elseif ($value = CRM_Utils_Array
::value($key, $params)) {
84 foreach ($params as $subParam) {
85 if (is_array($subParam) &&
86 $value = self
::retrieveValueRecursive($subParam, $key)
96 * Wraps and slightly changes the behavior of PHP's array_search().
98 * This function reproduces the behavior of array_search() from PHP prior to
99 * version 4.2.0, which was to return NULL on failure. This function also
100 * checks that $list is an array before attempting to search it.
104 * @param mixed $value
105 * The value to search for.
107 * The array to be searched.
109 * @return int|string|null
110 * Returns the key, which could be an int or a string, or NULL on failure.
112 static function key($value, &$list) {
113 if (is_array($list)) {
114 $key = array_search($value, $list);
116 // array_search returns key if found, false otherwise
117 // it may return values like 0 or empty string which
118 // evaluates to false
119 // hence we must use identical comparison operator
120 return ($key === FALSE) ?
NULL : $key;
126 * Builds an XML fragment representing an array.
128 * Depending on the nature of the keys of the array (and its sub-arrays,
129 * if any) the XML fragment may not be valid.
132 * The array to be serialized.
134 * (optional) Indentation depth counter.
135 * @param string $seperator
136 * (optional) String to be appended after open/close tags.
141 * XML fragment representing $list.
143 static function &xml(&$list, $depth = 1, $seperator = "\n") {
145 foreach ($list as $name => $value) {
146 $xml .= str_repeat(' ', $depth * 4);
147 if (is_array($value)) {
148 $xml .= "<{$name}>{$seperator}";
149 $xml .= self
::xml($value, $depth +
1, $seperator);
150 $xml .= str_repeat(' ', $depth * 4);
151 $xml .= "</{$name}>{$seperator}";
154 // make sure we escape value
155 $value = self
::escapeXML($value);
156 $xml .= "<{$name}>$value</{$name}>{$seperator}";
163 * Sanitizes a string for serialization in CRM_Utils_Array::xml().
165 * Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A'
168 * @param string $value
169 * String to be sanitized.
172 * Sanitized version of $value.
174 static function escapeXML($value) {
179 $src = array('&', '<', '>', '\ 1');
180 $dst = array('&', '<', '>', ',');
183 return str_replace($src, $dst, $value);
187 * Converts a nested array to a flat array.
189 * The nested structure is preserved in the string values of the keys of the
192 * Example nested array:
217 * Corresponding flattened array:
223 * [asdf.merp] => bleep
224 * [asdf.quack.0] => 1
225 * [asdf.quack.1] => 2
226 * [asdf.quack.2] => 3
231 * Array to be flattened.
234 * @param string $prefix
235 * (optional) String to prepend to keys.
236 * @param string $seperator
237 * (optional) String that separates the concatenated keys.
241 static function flatten(&$list, &$flat, $prefix = '', $seperator = ".") {
242 foreach ($list as $name => $value) {
243 $newPrefix = ($prefix) ?
$prefix . $seperator . $name : $name;
244 if (is_array($value)) {
245 self
::flatten($value, $flat, $newPrefix, $seperator);
248 if (!empty($value)) {
249 $flat[$newPrefix] = $value;
256 * Converts an array with path-like keys into a tree of arrays.
258 * This function is the inverse of CRM_Utils_Array::flatten().
260 * @param string $delim
263 * A one-dimensional array indexed by string keys
270 function unflatten($delim, &$arr) {
272 foreach ($arr as $key => $value) {
273 $path = explode($delim, $key);
275 while (count($path) > 1) {
276 $key = array_shift($path);
277 if (!isset($node[$key])) {
278 $node[$key] = array();
280 $node = &$node[$key];
283 $key = array_shift($path);
284 $node[$key] = $value;
292 * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge
293 * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both
294 * exist but they are not both arrays, the value from $a1 overrides the
295 * value from $a2 and the value from $a2 is discarded.
298 * First array to be merged.
300 * Second array to be merged.
306 static function crmArrayMerge($a1, $a2) {
316 foreach ($a1 as $key => $value) {
317 if (array_key_exists($key, $a2) &&
318 is_array($a2[$key]) && is_array($a1[$key])
320 $a3[$key] = array_merge($a1[$key], $a2[$key]);
323 $a3[$key] = $a1[$key];
327 foreach ($a2 as $key => $value) {
328 if (array_key_exists($key, $a1)) {
329 // already handled in above loop
332 $a3[$key] = $a2[$key];
339 * Determines whether an array contains any sub-arrays.
342 * The array to inspect.
345 * True if $list contains at least one sub-array, false otherwise.
348 static function isHierarchical(&$list) {
349 foreach ($list as $n => $v) {
360 * @return bool TRUE if $subset is a subset of $superset
362 static function isSubset($subset, $superset) {
363 foreach ($subset as $expected) {
364 if (!in_array($expected, $superset)) {
372 * Recursively copies all values of an array into a new array.
374 * If the recursion depth limit is exceeded, the deep copy appears to
375 * succeed, but the copy process past the depth limit will be shallow.
377 * @params array $array
379 * @params int $maxdepth
380 * (optional) Recursion depth limit.
382 * (optional) Current recursion depth.
385 * The new copy of $array.
389 static function array_deep_copy(&$array, $maxdepth = 50, $depth = 0) {
390 if ($depth > $maxdepth) {
394 foreach ($array as $key => $value) {
395 if (is_array($value)) {
396 array_deep_copy($value, $copy[$key], $maxdepth, ++
$depth);
399 $copy[$key] = $value;
406 * Makes a shallow copy of a variable, returning the copy by value.
408 * In some cases, functions return an array by reference, but we really don't
409 * want to receive a reference.
411 * @param $array mixed
412 * Something to return a copy of.
417 static function breakReference($array) {
423 * Removes a portion of an array.
425 * This function is similar to PHP's array_splice(), with some differences:
426 * - Array keys that are not removed are preserved. The PHP built-in
427 * function only preserves values.
428 * - The portion of the array to remove is specified by start and end
429 * index rather than offset and length.
430 * - There is no ability to specify data to replace the removed portion.
432 * The behavior given an associative array would probably not be useful.
434 * @param array $params
435 * Array to manipulate.
437 * First index to remove.
439 * Last index to remove.
443 static function crmArraySplice(&$params, $start, $end) {
444 // verify start and end index
448 if ($end > count($params)) {
449 $end = count($params);
454 // procees unset operation
455 foreach ($params as $key => $value) {
456 if ($i >= $start && $i < $end) {
457 unset($params[$key]);
464 * Searches an array recursively in an optionally case-insensitive manner.
466 * @param string $value
467 * Value to search for.
468 * @param array $params
469 * Array to search within.
470 * @param bool $caseInsensitive
471 * (optional) Whether to search in a case-insensitive manner.
474 * True if $value was found, false otherwise.
478 static function crmInArray($value, $params, $caseInsensitive = TRUE) {
479 foreach ($params as $item) {
480 if (is_array($item)) {
481 $ret = crmInArray($value, $item, $caseInsensitive);
484 $ret = ($caseInsensitive) ?
strtolower($item) == strtolower($value) : $item == $value;
494 * This function is used to convert associative array names to values
497 * This function is used by both the web form layer and the api. Note that
498 * the api needs the name => value conversion, also the view layer typically
499 * requires value => name conversion
501 static function lookupValue(&$defaults, $property, $lookup, $reverse) {
502 $id = $property . '_id';
504 $src = $reverse ?
$property : $id;
505 $dst = $reverse ?
$id : $property;
507 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER
))) {
511 $look = $reverse ?
array_flip($lookup) : $lookup;
513 //trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
515 foreach ($look as $k => $v) {
516 $newLook[trim($k, ".")] = $v;
521 if (is_array($look)) {
522 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER
))) {
527 $tempLook = array_change_key_case($look, CASE_LOWER
);
529 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
534 * Checks whether an array is empty.
536 * An array is empty if its values consist only of NULL and empty sub-arrays.
537 * Containing a non-NULL value or non-empty array makes an array non-empty.
539 * If something other than an array is passed, it is considered to be empty.
541 * If nothing is passed at all, the default value provided is empty.
543 * @param array $array
544 * (optional) Array to be checked for emptiness.
547 * True if the array is empty.
550 static function crmIsEmptyArray($array = array()) {
551 if (!is_array($array)) {
554 foreach ($array as $element) {
555 if (is_array($element)) {
556 if (!self
::crmIsEmptyArray($element)) {
560 elseif (isset($element)) {
568 * Determines the maximum depth of nested arrays in a multidimensional array.
570 * The mechanism for determining depth will be confused if the array
571 * contains keys or values with the left brace '{' character. This will
572 * cause the depth to be over-reported.
574 * @param array $array
575 * The array to examine.
578 * The maximum nested array depth found.
582 static function getLevelsArray($array) {
583 if (!is_array($array)) {
586 $jsonString = json_encode($array);
587 $parts = explode("}", $jsonString);
589 foreach ($parts as $part) {
590 $countLevels = substr_count($part, "{");
591 if ($countLevels > $max) {
599 * Sorts an associative array of arrays by an attribute using strnatcmp().
601 * @param array $array
602 * Array to be sorted.
603 * @param string $field
604 * Name of the attribute used for sorting.
609 static function crmArraySortByField($array, $field) {
610 $code = "return strnatcmp(\$a['$field'], \$b['$field']);";
611 uasort($array, create_function('$a,$b', $code));
616 * Recursively removes duplicate values from a multi-dimensional array.
618 * @param array $array
619 * The input array possibly containing duplicate values.
622 * The input array with duplicate values removed.
624 static function crmArrayUnique($array) {
625 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
626 foreach ($result as $key => $value) {
627 if (is_array($value)) {
628 $result[$key] = self
::crmArrayUnique($value);
635 * Sorts an array and maintains index association (with localization).
637 * Uses Collate from the PECL "intl" package, if available, for UTF-8
638 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
640 * On Debian/Ubuntu: apt-get install php5-intl
642 * @param array $array
643 * (optional) Array to be sorted.
648 static function asort($array = array()) {
649 $lcMessages = CRM_Utils_System
::getUFLocale();
651 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
652 $collator = new Collator($lcMessages . '.utf8');
653 $collator->asort($array);
656 // This calls PHP's built-in asort().
664 * Unsets an arbitrary list of array elements from an associative array.
666 * @param array $items
667 * The array from which to remove items.
668 * @param string[]|string $key,...
669 * When passed a string, unsets $items[$key].
670 * When passed an array of strings, unsets $items[$k] for each string $k
673 static function remove(&$items) {
674 foreach (func_get_args() as $n => $key) {
675 // Skip argument 0 ($items) by testing $n for truth.
676 if ($n && is_array($key)) {
677 foreach($key as $k) {
688 * Builds an array-tree which indexes the records in an array.
690 * @param string[] $keys
691 * Properties by which to index.
692 * @param object|array $records
695 * Multi-dimensional array, with one layer for each key.
697 static function index($keys, $records) {
698 $final_key = array_pop($keys);
701 foreach ($records as $record) {
703 foreach ($keys as $key) {
704 if (is_array($record)) {
705 $keyvalue = $record[$key];
707 $keyvalue = $record->{$key};
709 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
710 $node[$keyvalue] = array();
712 $node = &$node[$keyvalue];
714 if (is_array($record)) {
715 $node[ $record[$final_key] ] = $record;
717 $node[ $record->{$final_key} ] = $record;
724 * Iterates over a list of records and returns the value of some property.
726 * @param string $prop
727 * Property to retrieve.
728 * @param array|object $records
732 * Keys are the original keys of $records; values are the $prop values.
734 static function collect($prop, $records) {
736 foreach ($records as $key => $record) {
737 if (is_object($record)) {
738 $result[$key] = $record->{$prop};
740 $result[$key] = $record[$prop];
747 * Generate a string representation of an array.
749 * @param array $pairs
750 * Array to stringify.
751 * @param string $l1Delim
752 * String to use to separate key/value pairs from one another.
753 * @param string $l2Delim
754 * String to use to separate keys from values within each key/value pair.
759 static function implodeKeyValue($l1Delim, $l2Delim, $pairs) {
761 foreach ($pairs as $key => $value) {
762 $exprs[] = $key . $l2Delim . $value;
764 return implode($l1Delim, $exprs);
768 * Trims delimiters from a string and then splits it using explode().
770 * This method works mostly like PHP's built-in explode(), except that
771 * surrounding delimiters are trimmed before explode() is called.
773 * Also, if an array or NULL is passed as the $values parameter, the value is
774 * returned unmodified rather than being passed to explode().
776 * @param array|null|string $values
777 * The input string (or an array, or NULL).
778 * @param string $delim
779 * (optional) The boundary string.
782 * An array of strings produced by explode(), or the unmodified input
785 static function explodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
786 if ($values === NULL) {
789 // If we already have an array, no need to continue
790 if (is_array($values)) {
793 return explode($delim, trim((string) $values, $delim));
797 * Joins array elements with a string, adding surrounding delimiters.
799 * This method works mostly like PHP's built-in implode(), but the generated
800 * string is surrounded by delimiter characters. Also, if NULL is passed as
801 * the $values parameter, NULL is returned.
803 * @param mixed $values
804 * Array to be imploded. If a non-array is passed, it will be cast to an
806 * @param string $delim
807 * Delimiter to be used for implode() and which will surround the output
810 * @return string|NULL
811 * The generated string, or NULL if NULL was passed as $values parameter.
813 static function implodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
814 if ($values === NULL) {
817 // If we already have a string, strip $delim off the ends so it doesn't get added twice
818 if (is_string($values)) {
819 $values = trim($values, $delim);
821 return $delim . implode($delim, (array) $values) . $delim;
825 * Modifies a key in an array while preserving the key order.
827 * By default when an element is added to an array, it is added to the end.
828 * This method allows for changing an existing key while preserving its
829 * position in the array.
831 * The array is both modified in-place and returned.
833 * @param array $elementArray
834 * Array to manipulate.
835 * @param string $oldKey
836 * Old key to be replaced.
837 * @param string $newKey
838 * Replacement key string.
841 * Throws a generic Exception if $oldKey is not found in $elementArray.
844 * The manipulated array.
846 static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
847 $keys = array_keys($elementArray);
848 if (FALSE === $index = array_search($oldKey, $keys)) {
849 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
851 $keys[$index] = $newKey;
852 $elementArray = array_combine($keys, array_values($elementArray));
853 return $elementArray;
857 * Searches array keys by regex, returning the value of the first match.
859 * Given a regular expression and an array, this method searches the keys
860 * of the array using the regular expression. The first match is then used
861 * to index into the array, and the associated value is retrieved and
862 * returned. If no matches are found, or if something other than an array
863 * is passed, then a default value is returned. Unless otherwise specified,
864 * the default value is NULL.
866 * @param string $regexKey
867 * The regular expression to use when searching for matching keys.
869 * The array whose keys will be searched.
870 * @param mixed $default
871 * (optional) The default value to return if the regex does not match an
872 * array key, or if something other than an array is passed.
877 static function valueByRegexKey($regexKey, $list, $default = NULL) {
878 if (is_array($list) && $regexKey) {
879 $matches = preg_grep($regexKey, array_keys($list));
880 $key = reset($matches);
881 return ($key && array_key_exists($key, $list)) ?
$list[$key] : $default;
887 * Generates the Cartesian product of zero or more vectors.
889 * @param array $dimensions
890 * List of dimensions to multiply.
891 * Each key is a dimension name; each value is a vector.
892 * @param array $template
893 * (optional) A base set of values included in every output.
896 * Each item is a distinct combination of values from $dimensions.
898 * For example, the product of
901 * bg => {white, black}
905 * {fg => red, bg => white},
906 * {fg => red, bg => black},
907 * {fg => blue, bg => white},
908 * {fg => blue, bg => black}
911 static function product($dimensions, $template = array()) {
912 if (empty($dimensions)) {
913 return array($template);
916 foreach ($dimensions as $key => $value) {
918 $firstValues = $value;
921 unset($dimensions[$key]);
924 foreach ($firstValues as $firstValue) {
925 foreach (self
::product($dimensions, $template) as $result) {
926 $result[$firstKey] = $firstValue;
927 $results[] = $result;