3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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.
137 * XML fragment representing $list.
139 public static function &xml(&$list, $depth = 1, $seperator = "\n") {
141 foreach ($list as $name => $value) {
142 $xml .= str_repeat(' ', $depth * 4);
143 if (is_array($value)) {
144 $xml .= "<{$name}>{$seperator}";
145 $xml .= self
::xml($value, $depth +
1, $seperator);
146 $xml .= str_repeat(' ', $depth * 4);
147 $xml .= "</{$name}>{$seperator}";
150 // make sure we escape value
151 $value = self
::escapeXML($value);
152 $xml .= "<{$name}>$value</{$name}>{$seperator}";
159 * Sanitizes a string for serialization in CRM_Utils_Array::xml().
161 * Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A'
164 * @param string $value
165 * String to be sanitized.
168 * Sanitized version of $value.
170 public static function escapeXML($value) {
175 $src = array('&', '<', '>', '\ 1');
176 $dst = array('&', '<', '>', ',');
179 return str_replace($src, $dst, $value);
183 * Converts a nested array to a flat array.
185 * The nested structure is preserved in the string values of the keys of the
188 * Example nested array:
213 * Corresponding flattened array:
219 * [asdf.merp] => bleep
220 * [asdf.quack.0] => 1
221 * [asdf.quack.1] => 2
222 * [asdf.quack.2] => 3
227 * Array to be flattened.
230 * @param string $prefix
231 * (optional) String to prepend to keys.
232 * @param string $seperator
233 * (optional) String that separates the concatenated keys.
235 public static function flatten(&$list, &$flat, $prefix = '', $seperator = ".") {
236 foreach ($list as $name => $value) {
237 $newPrefix = ($prefix) ?
$prefix . $seperator . $name : $name;
238 if (is_array($value)) {
239 self
::flatten($value, $flat, $newPrefix, $seperator);
242 if (!empty($value)) {
243 $flat[$newPrefix] = $value;
250 * Converts an array with path-like keys into a tree of arrays.
252 * This function is the inverse of CRM_Utils_Array::flatten().
254 * @param string $delim
257 * A one-dimensional array indexed by string keys
262 public function unflatten($delim, &$arr) {
264 foreach ($arr as $key => $value) {
265 $path = explode($delim, $key);
267 while (count($path) > 1) {
268 $key = array_shift($path);
269 if (!isset($node[$key])) {
270 $node[$key] = array();
272 $node = &$node[$key];
275 $key = array_shift($path);
276 $node[$key] = $value;
284 * If $a1[foo] and $a2[foo] both exist and are both arrays, the merge
285 * process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both
286 * exist but they are not both arrays, the value from $a1 overrides the
287 * value from $a2 and the value from $a2 is discarded.
290 * First array to be merged.
292 * Second array to be merged.
297 public static function crmArrayMerge($a1, $a2) {
307 foreach ($a1 as $key => $value) {
308 if (array_key_exists($key, $a2) &&
309 is_array($a2[$key]) && is_array($a1[$key])
311 $a3[$key] = array_merge($a1[$key], $a2[$key]);
314 $a3[$key] = $a1[$key];
318 foreach ($a2 as $key => $value) {
319 if (array_key_exists($key, $a1)) {
320 // already handled in above loop
323 $a3[$key] = $a2[$key];
330 * Determines whether an array contains any sub-arrays.
333 * The array to inspect.
336 * True if $list contains at least one sub-array, false otherwise.
338 public static function isHierarchical(&$list) {
339 foreach ($list as $n => $v) {
351 * TRUE if $subset is a subset of $superset
353 public static function isSubset($subset, $superset) {
354 foreach ($subset as $expected) {
355 if (!in_array($expected, $superset)) {
363 * Searches an array recursively in an optionally case-insensitive manner.
365 * @param string $value
366 * Value to search for.
367 * @param array $params
368 * Array to search within.
369 * @param bool $caseInsensitive
370 * (optional) Whether to search in a case-insensitive manner.
373 * True if $value was found, false otherwise.
375 public static function crmInArray($value, $params, $caseInsensitive = TRUE) {
376 foreach ($params as $item) {
377 if (is_array($item)) {
378 $ret = crmInArray($value, $item, $caseInsensitive);
381 $ret = ($caseInsensitive) ?
strtolower($item) == strtolower($value) : $item == $value;
391 * convert associative array names to values.
394 * This function is used by both the web form layer and the api. Note that
395 * the api needs the name => value conversion, also the view layer typically
396 * requires value => name conversion
398 public static function lookupValue(&$defaults, $property, $lookup, $reverse) {
399 $id = $property . '_id';
401 $src = $reverse ?
$property : $id;
402 $dst = $reverse ?
$id : $property;
404 if (!array_key_exists(strtolower($src), array_change_key_case($defaults, CASE_LOWER
))) {
408 $look = $reverse ?
array_flip($lookup) : $lookup;
410 //trim lookup array, ignore . ( fix for CRM-1514 ), eg for prefix/suffix make sure Dr. and Dr both are valid
412 foreach ($look as $k => $v) {
413 $newLook[trim($k, ".")] = $v;
418 if (is_array($look)) {
419 if (!array_key_exists(trim(strtolower($defaults[strtolower($src)]), '.'), array_change_key_case($look, CASE_LOWER
))) {
424 $tempLook = array_change_key_case($look, CASE_LOWER
);
426 $defaults[$dst] = $tempLook[trim(strtolower($defaults[strtolower($src)]), '.')];
431 * Checks whether an array is empty.
433 * An array is empty if its values consist only of NULL and empty sub-arrays.
434 * Containing a non-NULL value or non-empty array makes an array non-empty.
436 * If something other than an array is passed, it is considered to be empty.
438 * If nothing is passed at all, the default value provided is empty.
440 * @param array $array
441 * (optional) Array to be checked for emptiness.
444 * True if the array is empty.
446 public static function crmIsEmptyArray($array = array()) {
447 if (!is_array($array)) {
450 foreach ($array as $element) {
451 if (is_array($element)) {
452 if (!self
::crmIsEmptyArray($element)) {
456 elseif (isset($element)) {
464 * Sorts an associative array of arrays by an attribute using strnatcmp().
466 * @param array $array
467 * Array to be sorted.
468 * @param string $field
469 * Name of the attribute used for sorting.
474 public static function crmArraySortByField($array, $field) {
475 $code = "return strnatcmp(\$a['$field'], \$b['$field']);";
476 uasort($array, create_function('$a,$b', $code));
481 * Recursively removes duplicate values from a multi-dimensional array.
483 * @param array $array
484 * The input array possibly containing duplicate values.
487 * The input array with duplicate values removed.
489 public static function crmArrayUnique($array) {
490 $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
491 foreach ($result as $key => $value) {
492 if (is_array($value)) {
493 $result[$key] = self
::crmArrayUnique($value);
500 * Sorts an array and maintains index association (with localization).
502 * Uses Collate from the PECL "intl" package, if available, for UTF-8
503 * sorting (e.g. list of countries). Otherwise calls PHP's asort().
505 * On Debian/Ubuntu: apt-get install php5-intl
507 * @param array $array
508 * (optional) Array to be sorted.
513 public static function asort($array = array()) {
514 $lcMessages = CRM_Utils_System
::getUFLocale();
516 if ($lcMessages && $lcMessages != 'en_US' && class_exists('Collator')) {
517 $collator = new Collator($lcMessages . '.utf8');
518 $collator->asort($array);
521 // This calls PHP's built-in asort().
529 * Unsets an arbitrary list of array elements from an associative array.
531 * @param array $items
532 * The array from which to remove items.
535 * When passed a string, unsets $items[$key].
536 * When passed an array of strings, unsets $items[$k] for each string $k in the array.
538 public static function remove(&$items) {
539 foreach (func_get_args() as $n => $key) {
540 // Skip argument 0 ($items) by testing $n for truth.
541 if ($n && is_array($key)) {
542 foreach ($key as $k) {
553 * Builds an array-tree which indexes the records in an array.
555 * @param string[] $keys
556 * Properties by which to index.
557 * @param object|array $records
560 * Multi-dimensional array, with one layer for each key.
562 public static function index($keys, $records) {
563 $final_key = array_pop($keys);
566 foreach ($records as $record) {
568 foreach ($keys as $key) {
569 if (is_array($record)) {
570 $keyvalue = isset($record[$key]) ?
$record[$key] : NULL;
573 $keyvalue = isset($record->{$key}) ?
$record->{$key} : NULL;
575 if (isset($node[$keyvalue]) && !is_array($node[$keyvalue])) {
576 $node[$keyvalue] = array();
578 $node = &$node[$keyvalue];
580 if (is_array($record)) {
581 $node[$record[$final_key]] = $record;
584 $node[$record->{$final_key}] = $record;
591 * Iterates over a list of records and returns the value of some property.
593 * @param string $prop
594 * Property to retrieve.
595 * @param array|object $records
599 * Keys are the original keys of $records; values are the $prop values.
601 public static function collect($prop, $records) {
603 if (is_array($records)) {
604 foreach ($records as $key => $record) {
605 if (is_object($record)) {
606 $result[$key] = $record->{$prop};
609 $result[$key] = $record[$prop];
617 * Trims delimiters from a string and then splits it using explode().
619 * This method works mostly like PHP's built-in explode(), except that
620 * surrounding delimiters are trimmed before explode() is called.
622 * Also, if an array or NULL is passed as the $values parameter, the value is
623 * returned unmodified rather than being passed to explode().
625 * @param array|null|string $values
626 * The input string (or an array, or NULL).
627 * @param string $delim
628 * (optional) The boundary string.
631 * An array of strings produced by explode(), or the unmodified input
634 public static function explodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
635 if ($values === NULL) {
638 // If we already have an array, no need to continue
639 if (is_array($values)) {
642 // Empty string -> empty array
643 if ($values === '') {
646 return explode($delim, trim((string) $values, $delim));
650 * Joins array elements with a string, adding surrounding delimiters.
652 * This method works mostly like PHP's built-in implode(), but the generated
653 * string is surrounded by delimiter characters. Also, if NULL is passed as
654 * the $values parameter, NULL is returned.
656 * @param mixed $values
657 * Array to be imploded. If a non-array is passed, it will be cast to an
659 * @param string $delim
660 * Delimiter to be used for implode() and which will surround the output
663 * @return string|NULL
664 * The generated string, or NULL if NULL was passed as $values parameter.
666 public static function implodePadded($values, $delim = CRM_Core_DAO
::VALUE_SEPARATOR
) {
667 if ($values === NULL) {
670 // If we already have a string, strip $delim off the ends so it doesn't get added twice
671 if (is_string($values)) {
672 $values = trim($values, $delim);
674 return $delim . implode($delim, (array) $values) . $delim;
678 * Modifies a key in an array while preserving the key order.
680 * By default when an element is added to an array, it is added to the end.
681 * This method allows for changing an existing key while preserving its
682 * position in the array.
684 * The array is both modified in-place and returned.
686 * @param array $elementArray
687 * Array to manipulate.
688 * @param string $oldKey
689 * Old key to be replaced.
690 * @param string $newKey
691 * Replacement key string.
694 * Throws a generic Exception if $oldKey is not found in $elementArray.
697 * The manipulated array.
699 public static function crmReplaceKey(&$elementArray, $oldKey, $newKey) {
700 $keys = array_keys($elementArray);
701 if (FALSE === $index = array_search($oldKey, $keys)) {
702 throw new Exception(sprintf('key "%s" does not exit', $oldKey));
704 $keys[$index] = $newKey;
705 $elementArray = array_combine($keys, array_values($elementArray));
706 return $elementArray;
710 * Searches array keys by regex, returning the value of the first match.
712 * Given a regular expression and an array, this method searches the keys
713 * of the array using the regular expression. The first match is then used
714 * to index into the array, and the associated value is retrieved and
715 * returned. If no matches are found, or if something other than an array
716 * is passed, then a default value is returned. Unless otherwise specified,
717 * the default value is NULL.
719 * @param string $regexKey
720 * The regular expression to use when searching for matching keys.
722 * The array whose keys will be searched.
723 * @param mixed $default
724 * (optional) The default value to return if the regex does not match an
725 * array key, or if something other than an array is passed.
730 public static function valueByRegexKey($regexKey, $list, $default = NULL) {
731 if (is_array($list) && $regexKey) {
732 $matches = preg_grep($regexKey, array_keys($list));
733 $key = reset($matches);
734 return ($key && array_key_exists($key, $list)) ?
$list[$key] : $default;
740 * Generates the Cartesian product of zero or more vectors.
742 * @param array $dimensions
743 * List of dimensions to multiply.
744 * Each key is a dimension name; each value is a vector.
745 * @param array $template
746 * (optional) A base set of values included in every output.
749 * Each item is a distinct combination of values from $dimensions.
751 * For example, the product of
754 * bg => {white, black}
758 * {fg => red, bg => white},
759 * {fg => red, bg => black},
760 * {fg => blue, bg => white},
761 * {fg => blue, bg => black}
764 public static function product($dimensions, $template = array()) {
765 if (empty($dimensions)) {
766 return array($template);
769 foreach ($dimensions as $key => $value) {
771 $firstValues = $value;
774 unset($dimensions[$key]);
777 foreach ($firstValues as $firstValue) {
778 foreach (self
::product($dimensions, $template) as $result) {
779 $result[$firstKey] = $firstValue;
780 $results[] = $result;
788 * Get the first element of an array.
790 * @param array $array
793 public static function first($array) {
794 foreach ($array as $value) {
801 * Extract any $keys from $array and copy to a new array.
803 * Note: If a $key does not appear in $array, then it will
804 * not appear in the result.
806 * @param array $array
808 * List of keys to copy.
811 public static function subset($array, $keys) {
813 foreach ($keys as $key) {
814 if (isset($array[$key])) {
815 $result[$key] = $array[$key];
822 * Transform an associative array of key=>value pairs into a non-associative array of arrays.
823 * This is necessary to preserve sort order when sending an array through json_encode.
825 * @param array $associative
826 * @param string $keyName
827 * @param string $valueName
830 public static function makeNonAssociative($associative, $keyName = 'key', $valueName = 'value') {
832 foreach ($associative as $key => $val) {
833 $output[] = array($keyName => $key, $valueName => $val);
839 * Diff multidimensional arrays
840 * ( array_diff does not support multidimensional array)
842 * @param array $array1
843 * @param array $array2
846 public static function multiArrayDiff($array1, $array2) {
847 $arrayDiff = array();
848 foreach ($array1 as $mKey => $mValue) {
849 if (array_key_exists($mKey, $array2)) {
850 if (is_array($mValue)) {
851 $recursiveDiff = self
::multiArrayDiff($mValue, $array2[$mKey]);
852 if (count($recursiveDiff)) {
853 $arrayDiff[$mKey] = $recursiveDiff;
857 if ($mValue != $array2[$mKey]) {
858 $arrayDiff[$mKey] = $mValue;
863 $arrayDiff[$mKey] = $mValue;
870 * Given a 2-dimensional matrix, create a new matrix with a restricted list of columns.
872 * @param array $matrix
873 * All matrix data, as a list of rows.
874 * @param array $columns
875 * List of column names.
878 public static function filterColumns($matrix, $columns) {
880 foreach ($matrix as $pos => $oldRow) {
882 foreach ($columns as $column) {
883 $newRow[$column] = CRM_Utils_Array
::value($column, $oldRow);
885 $newRows[$pos] = $newRow;
891 * Rewrite the keys in an array by filtering through a function.
893 * @param array $array
894 * @param callable $func
895 * Function($key, $value). Returns the new key.
898 public static function rekey($array, $func) {
900 foreach ($array as $key => $value) {
901 $newKey = $func($key, $value);
902 $result[$newKey] = $value;