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 * Searches an array recursively in an optionally case-insensitive manner.
374 * @param string $value
375 * Value to search for.
376 * @param array $params
377 * Array to search within.
378 * @param bool $caseInsensitive
379 * (optional) Whether to search in a case-insensitive manner.
382 * True if $value was found, false otherwise.
386 static function crmInArray($value, $params, $caseInsensitive = TRUE) {
387 foreach ($params as $item) {
388 if (is_array($item)) {
389 $ret = crmInArray($value, $item, $caseInsensitive);
392 $ret = ($caseInsensitive) ?
strtolower($item) == strtolower($value) : $item == $value;
402 * This function is used to convert associative array names to values
405 * This function is used by both the web form layer and the api. Note that
406 * the api needs the name => value conversion, also the view layer typically
407 * requires value => name conversion
409 static function lookupValue(&$defaults, $property, $lookup, $reverse) {
410 $id = $property . '_id';
412 $src = $reverse ?
$property : $id;
413 $dst = $reverse ?
$id : $property;
415 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER
))) {
419 $look = $reverse ?
array_flip($lookup) : $lookup;
421 //trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
423 foreach ($look as $k => $v) {
424 $newLook[trim($k, ".")] = $v;
429 if (is_array($look)) {
430 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER
))) {
435 $tempLook = array_change_key_case($look, CASE_LOWER
);
437 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
442 * Checks whether an array is empty.
444 * An array is empty if its values consist only of NULL and empty sub-arrays.
445 * Containing a non-NULL value or non-empty array makes an array non-empty.
447 * If something other than an array is passed, it is considered to be empty.
449 * If nothing is passed at all, the default value provided is empty.
451 * @param array $array
452 * (optional) Array to be checked for emptiness.
455 * True if the array is empty.
458 static function crmIsEmptyArray($array = array()) {
459 if (!is_array($array)) {
462 foreach ($array as $element) {
463 if (is_array($element)) {
464 if (!self
::crmIsEmptyArray($element)) {
468 elseif (isset($element)) {
476 * Sorts an associative array of arrays by an attribute using strnatcmp().
478 * @param array $array
479 * Array to be sorted.
480 * @param string $field
481 * Name of the attribute used for sorting.
486 static function crmArraySortByField($array, $field) {
487 $code = "return strnatcmp(\$a['$field'], \$b['$field']);";
488 uasort($array, create_function('$a,$b', $code));
493 * Recursively removes duplicate values from a multi-dimensional array.
495 * @param array $array
496 * The input array possibly containing duplicate values.
499 * The input array with duplicate values removed.
501 static function crmArrayUnique($array) {
502 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
503 foreach ($result as $key => $value) {
504 if (is_array($value)) {
505 $result[$key] = self
::crmArrayUnique($value);
512 * Sorts an array and maintains index association (with localization).
514 * Uses Collate from the PECL "intl" package, if available, for UTF-8
515 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
517 * On Debian/Ubuntu: apt-get install php5-intl
519 * @param array $array
520 * (optional) Array to be sorted.
525 static function asort($array = array()) {
526 $lcMessages = CRM_Utils_System
::getUFLocale();
528 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
529 $collator = new Collator($lcMessages . '.utf8');
530 $collator->asort($array);
533 // This calls PHP's built-in asort().
541 * Unsets an arbitrary list of array elements from an associative array.
543 * @param array $items
544 * The array from which to remove items.
546 * @internal param string|\string[] $key When passed a string, unsets $items[$key].* When passed a string, unsets $items[$key].
547 * When passed an array of strings, unsets $items[$k] for each string $k
550 static function remove(&$items) {
551 foreach (func_get_args() as $n => $key) {
552 // Skip argument 0 ($items) by testing $n for truth.
553 if ($n && is_array($key)) {
554 foreach($key as $k) {
565 * Builds an array-tree which indexes the records in an array.
567 * @param string[] $keys
568 * Properties by which to index.
569 * @param object|array $records
572 * Multi-dimensional array, with one layer for each key.
574 static function index($keys, $records) {
575 $final_key = array_pop($keys);
578 foreach ($records as $record) {
580 foreach ($keys as $key) {
581 if (is_array($record)) {
582 $keyvalue = isset($record[$key]) ?
$record[$key] : NULL;
584 $keyvalue = isset($record->{$key}) ?
$record->{$key} : NULL;
586 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
587 $node[$keyvalue] = array();
589 $node = &$node[$keyvalue];
591 if (is_array($record)) {
592 $node[ $record[$final_key] ] = $record;
594 $node[ $record->{$final_key} ] = $record;
601 * Iterates over a list of records and returns the value of some property.
603 * @param string $prop
604 * Property to retrieve.
605 * @param array|object $records
609 * Keys are the original keys of $records; values are the $prop values.
611 static function collect($prop, $records) {
613 if (is_array($records)) {
614 foreach ($records as $key => $record) {
615 if (is_object($record)) {
616 $result[$key] = $record->{$prop};
618 $result[$key] = $record[$prop];
626 * Trims delimiters from a string and then splits it using explode().
628 * This method works mostly like PHP's built-in explode(), except that
629 * surrounding delimiters are trimmed before explode() is called.
631 * Also, if an array or NULL is passed as the $values parameter, the value is
632 * returned unmodified rather than being passed to explode().
634 * @param array|null|string $values
635 * The input string (or an array, or NULL).
636 * @param string $delim
637 * (optional) The boundary string.
640 * An array of strings produced by explode(), or the unmodified input
643 static function explodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
644 if ($values === NULL) {
647 // If we already have an array, no need to continue
648 if (is_array($values)) {
651 return explode($delim, trim((string) $values, $delim));
655 * Joins array elements with a string, adding surrounding delimiters.
657 * This method works mostly like PHP's built-in implode(), but the generated
658 * string is surrounded by delimiter characters. Also, if NULL is passed as
659 * the $values parameter, NULL is returned.
661 * @param mixed $values
662 * Array to be imploded. If a non-array is passed, it will be cast to an
664 * @param string $delim
665 * Delimiter to be used for implode() and which will surround the output
668 * @return string|NULL
669 * The generated string, or NULL if NULL was passed as $values parameter.
671 static function implodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
672 if ($values === NULL) {
675 // If we already have a string, strip $delim off the ends so it doesn't get added twice
676 if (is_string($values)) {
677 $values = trim($values, $delim);
679 return $delim . implode($delim, (array) $values) . $delim;
683 * Modifies a key in an array while preserving the key order.
685 * By default when an element is added to an array, it is added to the end.
686 * This method allows for changing an existing key while preserving its
687 * position in the array.
689 * The array is both modified in-place and returned.
691 * @param array $elementArray
692 * Array to manipulate.
693 * @param string $oldKey
694 * Old key to be replaced.
695 * @param string $newKey
696 * Replacement key string.
699 * Throws a generic Exception if $oldKey is not found in $elementArray.
702 * The manipulated array.
704 static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
705 $keys = array_keys($elementArray);
706 if (FALSE === $index = array_search($oldKey, $keys)) {
707 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
709 $keys[$index] = $newKey;
710 $elementArray = array_combine($keys, array_values($elementArray));
711 return $elementArray;
715 * Searches array keys by regex, returning the value of the first match.
717 * Given a regular expression and an array, this method searches the keys
718 * of the array using the regular expression. The first match is then used
719 * to index into the array, and the associated value is retrieved and
720 * returned. If no matches are found, or if something other than an array
721 * is passed, then a default value is returned. Unless otherwise specified,
722 * the default value is NULL.
724 * @param string $regexKey
725 * The regular expression to use when searching for matching keys.
727 * The array whose keys will be searched.
728 * @param mixed $default
729 * (optional) The default value to return if the regex does not match an
730 * array key, or if something other than an array is passed.
738 * @param null $default
742 static function valueByRegexKey($regexKey, $list, $default = NULL) {
743 if (is_array($list) && $regexKey) {
744 $matches = preg_grep($regexKey, array_keys($list));
745 $key = reset($matches);
746 return ($key && array_key_exists($key, $list)) ?
$list[$key] : $default;
752 * Generates the Cartesian product of zero or more vectors.
754 * @param array $dimensions
755 * List of dimensions to multiply.
756 * Each key is a dimension name; each value is a vector.
757 * @param array $template
758 * (optional) A base set of values included in every output.
761 * Each item is a distinct combination of values from $dimensions.
763 * For example, the product of
766 * bg => {white, black}
770 * {fg => red, bg => white},
771 * {fg => red, bg => black},
772 * {fg => blue, bg => white},
773 * {fg => blue, bg => black}
776 static function product($dimensions, $template = array()) {
777 if (empty($dimensions)) {
778 return array($template);
781 foreach ($dimensions as $key => $value) {
783 $firstValues = $value;
786 unset($dimensions[$key]);
789 foreach ($firstValues as $firstValue) {
790 foreach (self
::product($dimensions, $template) as $result) {
791 $result[$firstKey] = $firstValue;
792 $results[] = $result;
800 * Get the first element of an array
802 * @param array $array
805 static function first($array) {
806 foreach ($array as $value) {