class CRM_Utils_Array

Provides a collection of static methods for array manipulation.

Methods

static mixed
value(string $key, array $list, mixed $default = NULL)

Returns $list[$key] if such element exists, or a default value otherwise.

static mixed
retrieveValueRecursive(array $params, string $key)

Recursively searches an array for a key, returning the first value found.

static int|string|null
key(mixed $value, array $list)

Wraps and slightly changes the behavior of PHP's array_search().

static string
xml(array $list, int $depth = 1, string $seperator = "\n")

Builds an XML fragment representing an array.

static string
escapeXML(string $value)

Sanitizes a string for serialization in CRM_Utils_Array::xml().

static 
flatten(array $list, array $flat, string $prefix = '', string $seperator = ".")

Converts a nested array to a flat array.

array
unflatten(string $delim, array $arr)

Converts an array with path-like keys into a tree of arrays.

static array
crmArrayMerge(array $a1, array $a2)

Merges two arrays.

static bool
isHierarchical(array $list)

Determines whether an array contains any sub-arrays.

static bool
isSubset(array $subset, array $superset)

Is array A a subset of array B.

static bool
crmInArray(string $value, array $params, bool $caseInsensitive = TRUE)

Searches an array recursively in an optionally case-insensitive manner.

static bool
lookupValue(array $defaults, string $property, $lookup, $reverse)

Convert associative array names to values and vice-versa.

static bool
crmIsEmptyArray(array $array = [])

Checks whether an array is empty.

static array
crmArraySortByField(array $array, string|array $field)

Sorts an associative array of arrays by an attribute using strnatcmp().

static array
crmArrayUnique(array $array)

Recursively removes duplicate values from a multi-dimensional array.

static array
asort(array $array = [])

Sorts an array and maintains index association (with localization).

static 
remove(array $items)

Unsets an arbitrary list of array elements from an associative array.

static array
index(string[] $keys, object|array $records)

Builds an array-tree which indexes the records in an array.

static array
collect(string $prop, array|object $records)

Iterates over a list of records and returns the value of some property.

static array
collectMethod(string $method, array|Traversable $objects, array $args = [])

Iterates over a list of objects and executes some method on each.

static array|null
explodePadded(array|null|string $values, string $delim = CRM_Core_DAO::VALUE_SEPARATOR)

Trims delimiters from a string and then splits it using explode().

static string|NULL
implodePadded(mixed $values, string $delim = CRM_Core_DAO::VALUE_SEPARATOR)

Joins array elements with a string, adding surrounding delimiters.

static array
crmReplaceKey(array $elementArray, string $oldKey, string $newKey)

Modifies a key in an array while preserving the key order.

static mixed
valueByRegexKey(string $regexKey, array $list, mixed $default = NULL)

Searches array keys by regex, returning the value of the first match.

static array
product(array $dimensions, array $template = [])

Generates the Cartesian product of zero or more vectors.

static mixed|NULL
first(array $array)

Get the first element of an array.

static array
subset(array $array, array $keys)

Extract any $keys from $array and copy to a new array.

static array
makeNonAssociative(array $associative, string $keyName = 'key', string $valueName = 'value')

Transform an associative array of key=>value pairs into a non-associative array of arrays.

static array
multiArrayDiff(array $array1, array $array2)

Diff multidimensional arrays (array_diff does not support multidimensional array)

static array
filterColumns(array $matrix, array $columns)

Given a 2-dimensional matrix, create a new matrix with a restricted list of columns.

static array
rekey(array $array, string|callable $indexBy)

Rewrite the keys in an array.

static 
extend(array|ArrayAccess $array, array $other)

Copy all properties of $other into $array (recursively).

static mixed
pathGet(array $values, array $path, mixed $default = NULL)

Get a single value from an array-tree.

static bool
pathIsset(array $values, array $path)

Check if a key isset which may be several layers deep.

static 
pathSet(array $values, array $pathParts, $value)

Set a single value in an array tree.

static array
toKeyValueRows(array $array, string $keyField = 'key', string $valueField = 'value') deprecated

Convert a simple dictionary into separate key+value records.

static 
formatArrayKeys(array $array) deprecated

Convert array where key(s) holds the actual value and value(s) as 1 into array of actual values Ex: array('foobar' => 1, 4 => 1) formatted into array('foobar', 4)

static array
convertCheckboxFormatToArray(array $input)

Convert the data format coming in from checkboxes to an array of values.

static array
encode_items(array $array)

Ensure that array is encoded in utf8 format.

static array
buildTree(array $elements, int|null $parentId = NULL)

Build tree of elements.

static array|null
findInTree(string $search, array $tree, string $field = 'id')

Find search string in tree.

Details

at line 53
static mixed value(string $key, array $list, mixed $default = NULL)

Returns $list[$key] if such element exists, or a default value otherwise.

If $list is not actually an array at all, then the default value is returned.

Parameters

string $key Key value to look up in the array.
array $list Array from which to look up a value.
mixed $default (optional) Value to return $list[$key] does not exist.

Return Value

mixed Can return any type, since $list might contain anything.

at line 74
static mixed retrieveValueRecursive(array $params, string $key)

Recursively searches an array for a key, returning the first value found.

If $params[$key] does not exist and $params contains arrays, descend into each array in a depth-first manner, in array iteration order.

Parameters

array $params The array to be searched.
string $key The key to search for.

Return Value

mixed The value of the key, or null if the key is not found.

at line 109
static int|string|null key(mixed $value, array $list)

Wraps and slightly changes the behavior of PHP's array_search().

This function reproduces the behavior of array_search() from PHP prior to version 4.2.0, which was to return NULL on failure. This function also checks that $list is an array before attempting to search it.

Parameters

mixed $value The value to search for.
array $list The array to be searched.

Return Value

int|string|null Returns the key, which could be an int or a string, or NULL on failure.

at line 138
static string xml(array $list, int $depth = 1, string $seperator = "\n")

Builds an XML fragment representing an array.

Depending on the nature of the keys of the array (and its sub-arrays, if any) the XML fragment may not be valid.

Parameters

array $list The array to be serialized.
int $depth (optional) Indentation depth counter.
string $seperator (optional) String to be appended after open/close tags.

Return Value

string XML fragment representing $list.

at line 169
static string escapeXML(string $value)

Sanitizes a string for serialization in CRM_Utils_Array::xml().

Replaces '&', '<', and '>' with their XML escape sequences. Replaces '^A' with a comma.

Parameters

string $value String to be sanitized.

Return Value

string Sanitized version of $value.

at line 234
static flatten(array $list, array $flat, string $prefix = '', string $seperator = ".")

Converts a nested array to a flat array.

The nested structure is preserved in the string values of the keys of the flat array.

Example nested array: Array ( [foo] => Array ( [0] => bar [1] => baz [2] => 42 )

[asdf] => Array
    (
        [merp] => bleep
        [quack] => Array
            (
                [0] => 1
                [1] => 2
                [2] => 3
            )

    )

[quux] => 999

)

Corresponding flattened array: Array ( [foo.0] => bar [foo.1] => baz [foo.2] => 42 [asdf.merp] => bleep [asdf.quack.0] => 1 [asdf.quack.1] => 2 [asdf.quack.2] => 3 [quux] => 999 )

Parameters

array $list Array to be flattened.
array $flat Destination array.
string $prefix (optional) String to prepend to keys.
string $seperator (optional) String that separates the concatenated keys.

at line 259
array unflatten(string $delim, array $arr)

Converts an array with path-like keys into a tree of arrays.

This function is the inverse of CRM_Utils_Array::flatten().

Parameters

string $delim A path delimiter
array $arr A one-dimensional array indexed by string keys

Return Value

array Array-encoded tree

at line 294
static array crmArrayMerge(array $a1, array $a2)

Merges two arrays.

If $a1[foo] and $a2[foo] both exist and are both arrays, the merge process recurses into those sub-arrays. If $a1[foo] and $a2[foo] both exist but they are not both arrays, the value from $a1 overrides the value from $a2 and the value from $a2 is discarded.

Parameters

array $a1 First array to be merged.
array $a2 Second array to be merged.

Return Value

array The merged array.

at line 335
static bool isHierarchical(array $list)

Determines whether an array contains any sub-arrays.

Parameters

array $list The array to inspect.

Return Value

bool True if $list contains at least one sub-array, false otherwise.

at line 353
static bool isSubset(array $subset, array $superset)

Is array A a subset of array B.

Parameters

array $subset
array $superset

Return Value

bool TRUE if $subset is a subset of $superset

at line 375
static bool crmInArray(string $value, array $params, bool $caseInsensitive = TRUE)

Searches an array recursively in an optionally case-insensitive manner.

Parameters

string $value Value to search for.
array $params Array to search within.
bool $caseInsensitive (optional) Whether to search in a case-insensitive manner.

Return Value

bool True if $value was found, false otherwise.

at line 402
static bool lookupValue(array $defaults, string $property, $lookup, $reverse)

Convert associative array names to values and vice-versa.

This function is used by by import functions and some webforms.

Parameters

array $defaults
string $property
$lookup
$reverse

Return Value

bool

at line 450
static bool crmIsEmptyArray(array $array = [])

Checks whether an array is empty.

An array is empty if its values consist only of NULL and empty sub-arrays. Containing a non-NULL value or non-empty array makes an array non-empty.

If something other than an array is passed, it is considered to be empty.

If nothing is passed at all, the default value provided is empty.

Parameters

array $array (optional) Array to be checked for emptiness.

Return Value

bool True if the array is empty.

at line 478
static array crmArraySortByField(array $array, string|array $field)

Sorts an associative array of arrays by an attribute using strnatcmp().

Parameters

array $array Array to be sorted.
string|array $field Name of the attribute used for sorting.

Return Value

array Sorted array

at line 501
static array crmArrayUnique(array $array)

Recursively removes duplicate values from a multi-dimensional array.

Parameters

array $array The input array possibly containing duplicate values.

Return Value

array The input array with duplicate values removed.

at line 525
static array asort(array $array = [])

Sorts an array and maintains index association (with localization).

Uses Collate from the PECL "intl" package, if available, for UTF-8 sorting (e.g. list of countries). Otherwise calls PHP's asort().

On Debian/Ubuntu: apt-get install php5-intl

Parameters

array $array (optional) Array to be sorted.

Return Value

array Sorted array.

at line 550
static remove(array $items)

Unsets an arbitrary list of array elements from an associative array.

Parameters

array $items The array from which to remove items.

Additional params: When passed a string, unsets $items[$key]. When passed an array of strings, unsets $items[$k] for each string $k in the array.

at line 574
static array index(string[] $keys, object|array $records)

Builds an array-tree which indexes the records in an array.

Parameters

string[] $keys Properties by which to index.
object|array $records

Return Value

array Multi-dimensional array, with one layer for each key.

at line 613
static array collect(string $prop, array|object $records)

Iterates over a list of records and returns the value of some property.

Parameters

string $prop Property to retrieve.
array|object $records A list of records.

Return Value

array Keys are the original keys of $records; values are the $prop values.

at line 647
static array collectMethod(string $method, array|Traversable $objects, array $args = [])

Iterates over a list of objects and executes some method on each.

Comparison: - This is like array_map(), except it executes the objects' method instead of a free-form callable. - This is like Array::collect(), except it uses a method instead of a property.

Parameters

string $method The method to execute.
array|Traversable $objects A list of objects.
array $args An optional list of arguments to pass to the method.

Return Value

array Keys are the original keys of $objects; values are the method results.

at line 675
static array|null explodePadded(array|null|string $values, string $delim = CRM_Core_DAO::VALUE_SEPARATOR)

Trims delimiters from a string and then splits it using explode().

This method works mostly like PHP's built-in explode(), except that surrounding delimiters are trimmed before explode() is called.

Also, if an array or NULL is passed as the $values parameter, the value is returned unmodified rather than being passed to explode().

Parameters

array|null|string $values The input string (or an array, or NULL).
string $delim (optional) The boundary string.

Return Value

array|null An array of strings produced by explode(), or the unmodified input array, or NULL.

at line 707
static string|NULL implodePadded(mixed $values, string $delim = CRM_Core_DAO::VALUE_SEPARATOR)

Joins array elements with a string, adding surrounding delimiters.

This method works mostly like PHP's built-in implode(), but the generated string is surrounded by delimiter characters. Also, if NULL is passed as the $values parameter, NULL is returned.

Parameters

mixed $values Array to be imploded. If a non-array is passed, it will be cast to an array.
string $delim Delimiter to be used for implode() and which will surround the output string.

Return Value

string|NULL The generated string, or NULL if NULL was passed as $values parameter.

at line 740
static array crmReplaceKey(array $elementArray, string $oldKey, string $newKey)

Modifies a key in an array while preserving the key order.

By default when an element is added to an array, it is added to the end. This method allows for changing an existing key while preserving its position in the array.

The array is both modified in-place and returned.

Parameters

array $elementArray Array to manipulate.
string $oldKey Old key to be replaced.
string $newKey Replacement key string.

Return Value

array The manipulated array.

Exceptions

Exception Throws a generic Exception if $oldKey is not found in $elementArray.

at line 771
static mixed valueByRegexKey(string $regexKey, array $list, mixed $default = NULL)

Searches array keys by regex, returning the value of the first match.

Given a regular expression and an array, this method searches the keys of the array using the regular expression. The first match is then used to index into the array, and the associated value is retrieved and returned. If no matches are found, or if something other than an array is passed, then a default value is returned. Unless otherwise specified, the default value is NULL.

Parameters

string $regexKey The regular expression to use when searching for matching keys.
array $list The array whose keys will be searched.
mixed $default (optional) The default value to return if the regex does not match an array key, or if something other than an array is passed.

Return Value

mixed The value found.

at line 805
static array product(array $dimensions, array $template = [])

Generates the Cartesian product of zero or more vectors.

Parameters

array $dimensions List of dimensions to multiply. Each key is a dimension name; each value is a vector.
array $template (optional) A base set of values included in every output.

Return Value

array Each item is a distinct combination of values from $dimensions.

For example, the product of { fg => {red, blue}, bg => {white, black} } would be { {fg => red, bg => white}, {fg => red, bg => black}, {fg => blue, bg => white}, {fg => blue, bg => black} }

at line 834
static mixed|NULL first(array $array)

Get the first element of an array.

Parameters

array $array

Return Value

mixed|NULL

at line 852
static array subset(array $array, array $keys)

Extract any $keys from $array and copy to a new array.

Note: If a $key does not appear in $array, then it will not appear in the result.

Parameters

array $array
array $keys List of keys to copy.

Return Value

array

at line 875
static array makeNonAssociative(array $associative, string $keyName = 'key', string $valueName = 'value')

Transform an associative array of key=>value pairs into a non-associative array of arrays.

This is necessary to preserve sort order when sending an array through json_encode.

Parameters

array $associative Ex: ['foo' => 'bar'].
string $keyName Ex: 'key'.
string $valueName Ex: 'value'.

Return Value

array Ex: [0 => ['key' => 'foo', 'value' => 'bar']].

at line 891
static array multiArrayDiff(array $array1, array $array2)

Diff multidimensional arrays (array_diff does not support multidimensional array)

Parameters

array $array1
array $array2

Return Value

array

at line 923
static array filterColumns(array $matrix, array $columns)

Given a 2-dimensional matrix, create a new matrix with a restricted list of columns.

Parameters

array $matrix All matrix data, as a list of rows.
array $columns List of column names.

Return Value

array

at line 943
static array rekey(array $array, string|callable $indexBy)

Rewrite the keys in an array.

Parameters

array $array
string|callable $indexBy Either the value to key by, or a function($key, $value) that returns the new key.

Return Value

array

at line 958
static extend(array|ArrayAccess $array, array $other)

Copy all properties of $other into $array (recursively).

Parameters

array|ArrayAccess $array
array $other

at line 980
static mixed pathGet(array $values, array $path, mixed $default = NULL)

Get a single value from an array-tree.

Parameters

array $values Ex: ['foo' => ['bar' => 123]].
array $path Ex: ['foo', 'bar'].
mixed $default

Return Value

mixed Ex 123.

at line 1000
static bool pathIsset(array $values, array $path)

Check if a key isset which may be several layers deep.

This is a helper for when the calling function does not know how many layers deep the path array is so cannot easily check.

Parameters

array $values
array $path

Return Value

bool

at line 1020
static pathSet(array $values, array $pathParts, $value)

Set a single value in an array tree.

Parameters

array $values Ex: ['foo' => ['bar' => 123]].
array $pathParts Ex: ['foo', 'bar'].
$value Ex: 456.

at line 1044
static array toKeyValueRows(array $array, string $keyField = 'key', string $valueField = 'value') deprecated

deprecated

Convert a simple dictionary into separate key+value records.

Parameters

array $array Ex: array('foo' => 'bar').
string $keyField Ex: 'key'.
string $valueField Ex: 'value'.

Return Value

array

at line 1057
static formatArrayKeys(array $array) deprecated

deprecated use convertCheckboxInputToArray instead (after testing) https://github.com/civicrm/civicrm-core/pull/8169

Convert array where key(s) holds the actual value and value(s) as 1 into array of actual values Ex: array('foobar' => 1, 4 => 1) formatted into array('foobar', 4)

Parameters

array $array

at line 1088
static array convertCheckboxFormatToArray(array $input)

Convert the data format coming in from checkboxes to an array of values.

The input format from check boxes looks like array('value1' => 1, 'value2' => 1). This function converts those values to array(''value1', 'value2).

The function will only alter the array if all values are equal to 1.

Parameters

array $input

Return Value

array

at line 1106
static array encode_items(array $array)

Ensure that array is encoded in utf8 format.

Parameters

array $array

Return Value

array $array utf8-encoded.

at line 1129
static array buildTree(array $elements, int|null $parentId = NULL)

Build tree of elements.

Parameters

array $elements
int|null $parentId

Return Value

array

at line 1154
static array|null findInTree(string $search, array $tree, string $field = 'id')

Find search string in tree.

Parameters

string $search
array $tree
string $field

Return Value

array|null