ArrayUtility

Class with helper functions for array handling

Table of Contents

Methods

arrayDiffAssocRecursive()  : array
Filters values off from first array that also exist in second array. Comparison is done by keys.
arrayDiffKeyRecursive()  : array
Filters keys off from first array that also exist in second array. Comparison is done by keys.
arrayExport()  : string
Exports an array as string.
assertAllArrayKeysAreValid()  : void
Validates the given $arrayToTest by checking if an element is not in $allowedArrayKeys.
convertBooleanStringsToBooleanRecursive()  : array
Recursively convert 'true' and 'false' strings to boolean values.
filterAndSortByNumericKeys()  : array
Takes a TypoScript array as input and returns an array which contains all integer properties found which had a value (not only properties). The output array will be sorted numerically.
filterByValueRecursive()  : array
Reduce an array by a search value and keep the array structure.
filterRecursive()  : array
Recursively filter an array
flatten()  : array
Converts a multidimensional array to a flat representation.
flattenPlain()  : array
Just like flatten, but not tailored for TypoScript but for plain simple arrays It is internal for now, as it needs to be decided how to deprecate/ rename flatten
getValueByPath()  : mixed
Returns a value by given path
intersectRecursive()  : array
Determine the intersections between two arrays, recursively comparing keys A complete sub array of $source will be preserved, if the key exists in $mask.
isAssociative()  : bool
Check whether the array has non-integer keys. If there is at least one string key, $array will be regarded as an associative array.
isValidPath()  : bool
Checks if a given path exists in array
keepItemsInArray()  : array
Filters an array to reduce its elements to match the condition.
mergeRecursiveWithOverrule()  : void
Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar values in the original array with the values of the overrule array.
naturalKeySortRecursive()  : bool
Sorts an array by key recursive - uses natural sort order (aAbB-zZ)
reIndexNumericArrayKeysRecursive()  : array
Reindex keys from the current nesting level if all keys within the current nesting level are integers.
remapArrayKeys()  : void
Rename Array keys with a given mapping table
removeArrayEntryByValue()  : array
Removes the value $cmpValue from the $array if found there. Returns the modified array
removeByPath()  : array
Remove a sub part from an array specified by path
removeNullValuesRecursive()  : array
Recursively remove keys if their value are NULL.
renumberKeysToAvoidLeapsIfKeysAreAllNumeric()  : array
Renumber the keys of an array to avoid leaps if keys are all numeric.
replaceAndAppendScalarValuesRecursive()  : array
Same as array_replace_recursive except that when in simple arrays (= YAML lists), the entries are appended (array_merge). The second array takes precedence in case of equal sub arrays.
setValueByPath()  : array
Modifies or sets a new value in an array by given path
sortArraysByKey()  : array
Sort an array of arrays by a given key using uasort
sortArrayWithIntegerKeys()  : array
If the array contains numerical keys only, sort it in ascending order
sortArrayWithIntegerKeysRecursive()  : array
Sort keys from the current nesting level if all keys within the current nesting level are integers.
sortByKeyRecursive()  : array
Sorts an array recursively by key
stripTagsFromValuesRecursive()  : array
Recursively translate values.
unflatten()  : array<string, mixed>
Converts a flat representation of an array to a multidimensional array.

Methods

arrayDiffAssocRecursive()

Filters values off from first array that also exist in second array. Comparison is done by keys.

public static arrayDiffAssocRecursive(array $array1, array $array2) : array

This method is a recursive version of php array_diff_assoc()

Parameters
$array1 : array

Source array

$array2 : array

Reduce source array by this array

Return values
array —

Source array reduced by values also present in second array, indexed by key

arrayDiffKeyRecursive()

Filters keys off from first array that also exist in second array. Comparison is done by keys.

public static arrayDiffKeyRecursive(array $array1, array $array2) : array

This method is a recursive version of php array_diff_key()

Parameters
$array1 : array

Source array

$array2 : array

Reduce source array by this array

Return values
array —

Source array reduced by keys also present in second array

arrayExport()

Exports an array as string.

public static arrayExport([array $array = [] ][, int $level = 0 ]) : string

Similar to var_export(), but representation follows the PSR-2 and TYPO3 core CGL.

See unit tests for detailed examples

Parameters
$array : array = []

Array to export

$level : int = 0

Internal level used for recursion, do not set from outside!

Tags
throws
RuntimeException
Return values
string —

String representation of array

assertAllArrayKeysAreValid()

Validates the given $arrayToTest by checking if an element is not in $allowedArrayKeys.

public static assertAllArrayKeysAreValid(array $arrayToTest, array $allowedArrayKeys) : void
Parameters
$arrayToTest : array
$allowedArrayKeys : array
Internal
Tags
throws
InvalidArgumentException

if an element in $arrayToTest is not in $allowedArrayKeys

convertBooleanStringsToBooleanRecursive()

Recursively convert 'true' and 'false' strings to boolean values.

public static convertBooleanStringsToBooleanRecursive(array $array) : array
Parameters
$array : array
Return values
array

filterAndSortByNumericKeys()

Takes a TypoScript array as input and returns an array which contains all integer properties found which had a value (not only properties). The output array will be sorted numerically.

public static filterAndSortByNumericKeys(array $setupArr[, bool $acceptAnyKeys = false ]) : array
Parameters
$setupArr : array

TypoScript array with numerical array in

$acceptAnyKeys : bool = false

If set, then a value is not required - the properties alone will be enough.

Tags
see
ContentObjectRenderer::cObjGet()
see
GifBuilder
Return values
array —

An array with all integer properties listed in numeric order.

filterByValueRecursive()

Reduce an array by a search value and keep the array structure.

public static filterByValueRecursive([mixed $needle = '' ][, array $haystack = [] ]) : array

Comparison is type strict:

  • For a given needle of type string, integer, array or boolean, value and value type must match to occur in result array
  • For a given object, an object within the array must be a reference to the same object to match (not just different instance of same class)

Example:

  • Needle: 'findMe'
  • Given array: array( 'foo' => 'noMatch', 'bar' => 'findMe', 'foobar => array( 'foo' => 'findMe', ), );
  • Result: array( 'bar' => 'findMe', 'foobar' => array( 'foo' => findMe', ), );

See the unit tests for more examples and expected behaviour

Parameters
$needle : mixed = ''

The value to search for

$haystack : array = []

The array in which to search

Return values
array —

$haystack array reduced matching $needle values

filterRecursive()

Recursively filter an array

public static filterRecursive(array $array[, callable|null $callback = null ][, 0|ARRAY_FILTER_USE_KEY|ARRAY_FILTER_USE_BOTH $mode = 0 ]) : array

Example: filterRecursive( ['a' => ['b' => null]], static fn ($item) => $item !== null, ARRAY_FILTER_USE_BOTH )

Parameters
$array : array
$callback : callable|null = null
$mode : 0|ARRAY_FILTER_USE_KEY|ARRAY_FILTER_USE_BOTH = 0
Tags
see
https://www.php.net/manual/en/function.array-filter.php
Return values
array

flatten()

Converts a multidimensional array to a flat representation.

public static flatten(array $array[, string $prefix = '' ][, bool $keepDots = false ]) : array
Parameters
$array : array

The (relative) array to be converted

$prefix : string = ''

The (relative) prefix to be used (e.g. 'section.')

$keepDots : bool = false
Tags
todo:

The current implementation isn't a generic array flatten method, but tailored for TypoScript flattening

todo:

It should be deprecated and removed and the required specialities should be put under the domain of TypoScript parsing

See unit tests for more details

Example:

  • array: array( 'first.' => array( 'second' => 1 ) )
  • result: array( 'first.second' => 1 )

Example:

  • array: array( 'first' => array( 'second' => 1 ) )
  • result: array( 'first.second' => 1 )
Return values
array

flattenPlain()

Just like flatten, but not tailored for TypoScript but for plain simple arrays It is internal for now, as it needs to be decided how to deprecate/ rename flatten

public static flattenPlain(array $array) : array
Parameters
$array : array
Internal
Return values
array

getValueByPath()

Returns a value by given path

public static getValueByPath(array $array, array|string $path[, string $delimiter = '/' ]) : mixed

Example

  • array: array( 'foo' => array( 'bar' => array( 'baz' => 42 ) ) );
  • path: foo/bar/baz
  • return: 42

If a path segments contains a delimiter character, the path segment must be enclosed by " (double quote), see unit tests for details

Parameters
$array : array

Input array

$path : array|string

Path within the array

$delimiter : string = '/'

Defined path delimiter, default /

Tags
throws
RuntimeException

if the path is empty, or if the path does not exist

throws
InvalidArgumentException

if the path is neither array nor string

intersectRecursive()

Determine the intersections between two arrays, recursively comparing keys A complete sub array of $source will be preserved, if the key exists in $mask.

public static intersectRecursive(array $source[, array $mask = [] ]) : array

See unit tests for more examples and edge cases.

Example:

  • source: array( 'key1' => 'bar', 'key2' => array( 'subkey1' => 'sub1', 'subkey2' => 'sub2', ), 'key3' => 'baz', )
  • mask: array( 'key1' => NULL, 'key2' => array( 'subkey1' => exists', ), )
  • return: array( 'key1' => 'bar', 'key2' => array( 'subkey1' => 'sub1', ), )
Parameters
$source : array

Source array

$mask : array = []

Array that has the keys which should be kept in the source array

Return values
array —

Keys which are present in both arrays with values of the source array

isAssociative()

Check whether the array has non-integer keys. If there is at least one string key, $array will be regarded as an associative array.

public static isAssociative(array $array) : bool
Parameters
$array : array
Internal
Return values
bool —

True in case a string key was found.

isValidPath()

Checks if a given path exists in array

public static isValidPath(array $array, array|string $path[, string $delimiter = '/' ]) : bool

Example:

  • array: array( 'foo' => array( 'bar' = 'test', ) );
  • path: 'foo/bar'
  • return: TRUE
Parameters
$array : array

Given array

$path : array|string

Path to test within the array

$delimiter : string = '/'

Delimiter for path, default /

Return values
bool —

TRUE if path exists in array

keepItemsInArray()

Filters an array to reduce its elements to match the condition.

public static keepItemsInArray(array $array, array|string|null $keepItems[, callable|null $getValueFunc = null ]) : array

The values in $keepItems can be optionally evaluated by a custom callback function.

Example (arguments used to call this function):

$array = array(
array('aa' => array('first', 'second'),
array('bb' => array('third', 'fourth'),
array('cc' => array('fifth', 'sixth'),
);
$keepItems = array('third');
$getValueFunc = function($value) { return $value[0]; }

Returns:

array(
array('bb' => array('third', 'fourth'),
)
Parameters
$array : array

$array The initial array to be filtered/reduced

$keepItems : array|string|null

The items which are allowed/kept in the array - accepts array or csv string

$getValueFunc : callable|null = null

(optional) Callback function used to get the value to keep

Return values
array —

The filtered/reduced array with the kept items

mergeRecursiveWithOverrule()

Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar values in the original array with the values of the overrule array.

public static mergeRecursiveWithOverrule(array &$original, array $overrule[, bool $addKeys = true ][, bool $includeEmptyValues = true ][, bool $enableUnsetFeature = true ]) : void

In case of identical keys, ie. keeping the values of the overrule array.

This method takes the original array by reference for speed optimization with large arrays

The differences to the existing PHP function array_merge_recursive() are:

  • Keys of the original array can be unset via the overrule array. ($enableUnsetFeature)
  • Much more control over what is actually merged. ($addKeys, $includeEmptyValues)
  • Elements or the original array get overwritten if the same key is present in the overrule array.
Parameters
$original : array

Original array. It will be modified by this method and contains the result afterwards!

$overrule : array

Overrule array, overruling the original array

$addKeys : bool = true

If set to FALSE, keys that are NOT found in $original will not be set. Thus only existing value can/will be overruled from overrule array.

$includeEmptyValues : bool = true

If set, values from $overrule will overrule if they are empty or zero.

$enableUnsetFeature : bool = true

If set, special values "__UNSET" can be used in the overrule array in order to unset array keys in the original array.

naturalKeySortRecursive()

Sorts an array by key recursive - uses natural sort order (aAbB-zZ)

public static naturalKeySortRecursive(array &$array) : bool
Parameters
$array : array

array to be sorted recursively, passed by reference

Return values
bool —

always TRUE

reIndexNumericArrayKeysRecursive()

Reindex keys from the current nesting level if all keys within the current nesting level are integers.

public static reIndexNumericArrayKeysRecursive(array $array) : array
Parameters
$array : array
Return values
array

remapArrayKeys()

Rename Array keys with a given mapping table

public static remapArrayKeys(array &$array, array $mappingTable) : void
Parameters
$array : array

Array by reference which should be remapped

$mappingTable : array

Array with remap information, array/$oldKey => $newKey)

removeArrayEntryByValue()

Removes the value $cmpValue from the $array if found there. Returns the modified array

public static removeArrayEntryByValue(array $array, string $cmpValue) : array
Parameters
$array : array

Array containing the values

$cmpValue : string

Value to search for and if found remove array entry where found.

Return values
array —

Output array with entries removed if search string is found

removeByPath()

Remove a sub part from an array specified by path

public static removeByPath(array $array, string $path[, string $delimiter = '/' ]) : array
Parameters
$array : array

Input array to manipulate

$path : string

Path to remove from array

$delimiter : string = '/'

Path delimiter

Tags
throws
RuntimeException
Return values
array —

Modified array

removeNullValuesRecursive()

Recursively remove keys if their value are NULL.

public static removeNullValuesRecursive(array $array) : array
Parameters
$array : array
Return values
array

renumberKeysToAvoidLeapsIfKeysAreAllNumeric()

Renumber the keys of an array to avoid leaps if keys are all numeric.

public static renumberKeysToAvoidLeapsIfKeysAreAllNumeric([array $array = [] ][, int $level = 0 ]) : array

Is called recursively for nested arrays.

Example:

Given array(0 => 'Zero' 1 => 'One', 2 => 'Two', 4 => 'Three') as input, it will return array(0 => 'Zero' 1 => 'One', 2 => 'Two', 3 => 'Three')

Will treat keys string representations of number (ie. '1') equal to the numeric value (ie. 1).

Example: Given array('0' => 'Zero', '1' => 'One' ) it will return array(0 => 'Zero', 1 => 'One')

Parameters
$array : array = []

Input array

$level : int = 0

Internal level used for recursion, do not set from outside!

Return values
array

replaceAndAppendScalarValuesRecursive()

Same as array_replace_recursive except that when in simple arrays (= YAML lists), the entries are appended (array_merge). The second array takes precedence in case of equal sub arrays.

public static replaceAndAppendScalarValuesRecursive(array $array1, array $array2) : array
Parameters
$array1 : array
$array2 : array
Internal
Return values
array

setValueByPath()

Modifies or sets a new value in an array by given path

public static setValueByPath(array $array, string|array|ArrayAccess $path, mixed $value[, string $delimiter = '/' ]) : array

Example:

  • array: array( 'foo' => array( 'bar' => 42, ), );
  • path: foo/bar
  • value: 23
  • return: array( 'foo' => array( 'bar' => 23, ), );
Parameters
$array : array

Input array to manipulate

$path : string|array|ArrayAccess

Path in array to search for

$value : mixed

Value to set at path location in array

$delimiter : string = '/'

Path delimiter

Tags
throws
RuntimeException
Return values
array —

Modified array

sortArraysByKey()

Sort an array of arrays by a given key using uasort

public static sortArraysByKey(array $arrays, string $key[, bool $ascending = true ]) : array
Parameters
$arrays : array

Array of arrays to sort

$key : string

Key to sort after

$ascending : bool = true

Set to TRUE for ascending order, FALSE for descending order

Tags
throws
RuntimeException
Return values
array —

Array of sorted arrays

sortArrayWithIntegerKeys()

If the array contains numerical keys only, sort it in ascending order

public static sortArrayWithIntegerKeys(array $array) : array
Parameters
$array : array
Return values
array

sortArrayWithIntegerKeysRecursive()

Sort keys from the current nesting level if all keys within the current nesting level are integers.

public static sortArrayWithIntegerKeysRecursive(array $array) : array
Parameters
$array : array
Return values
array

sortByKeyRecursive()

Sorts an array recursively by key

public static sortByKeyRecursive(array $array) : array
Parameters
$array : array

Array to sort recursively by key

Return values
array —

Sorted array

stripTagsFromValuesRecursive()

Recursively translate values.

public static stripTagsFromValuesRecursive(array $array) : array
Parameters
$array : array
Return values
array

unflatten()

Converts a flat representation of an array to a multidimensional array.

public static unflatten(array<string, mixed> $input[, string $delimiter = '.' ]) : array<string, mixed>

Example:

  • array: array( 'first.second' => 1 )

  • result: array( 'first.' => array( 'second' => 1 ) )

Parameters
$input : array<string, mixed>
$delimiter : string = '.'
Return values
array<string, mixed>
On this page

Search results