On this page
Class Hash
Library of array functions for manipulating and extracting data from arrays or 'sets' of data.
Hash provides an improved interface, more consistent and predictable set of features over Set. While it lacks the spotty support for pseudo Xpath, its more fully featured dot notation provides similar features in a more consistent implementation.
Link: https://book.cakephp.org/3.0/en/core-libraries/hash.html
Location: Utility/Hash.php
Method Summary
- Callback function for filtering.
- Check a key against a token.
- Checks whether or not $data matches the attribute patterns
- Merge helper function to reduce duplicated code between merge() and expand().
- Perform a simple insert/remove operation.
- Split token conditions
-
Helper method for sort() Squashes an array to a single hash so it can be sorted.
-
Apply a callback to a set of extracted values using
$function. The function will get the extracted values as the first argument. -
Test whether or not a given path exists in $data. This method uses the same path syntax as Hash::extract()
-
Creates an associative array using
$keyPathas the path to build its keys, and optionally$valuePathas path to get the values. If$valuePathis not specified, all values will be initialized to null (useful for Hash::merge). You can optionally group the values by what is obtained when following the path specified in$groupPath. - Determines if one array contains the exact keys and values of another.
-
Computes the difference between two complex arrays. This method differs from the built-in array_diff() in that it will preserve keys and work on multi-dimensional arrays.
-
Counts the dimensions of an array. Only considers the dimension of the first element in the array.
- Expands a flat array to a nested array.
-
Gets the values from an array matching the $path expression. The path expression is a dot separated expression, that can contain a set of patterns and expressions:
- Recursively filters a data set.
-
Collapses a multi-dimensional array into a single dimension, using a delimited array path for each array element's key, i.e. [['Foo' => ['Bar' => 'Far']]] becomes ['0.Foo.Bar' => 'Far'].)
-
Returns a formatted series of values extracted from
$data, using$formatas the format and$pathsas the values to extract. -
Get a single value specified by $path out of $data. Does not support the full dot notation feature set, but is faster for simple read operations.
-
Insert $values into an array with the given $path. You can use
{n}and{s}elements to insert $data multiple times. -
Map a callback across all elements in a set. Can be provided a path to only modify slices of the set.
-
Counts the dimensions of all array elements. Useful for finding the maximum number of dimensions in a mixed array.
-
This function can be thought of as a hybrid between PHP's
array_mergeandarray_merge_recursive. - Merges the difference between $data and $compare onto $data.
- Takes in a flat array and returns a nested array
- Normalizes an array, and converts it to a standard format.
- Checks to see if all the values in the array are numeric
-
Reduce a set of extracted values using
$function. -
Remove data matching $path from the $data array. You can use
{n}and{s}to remove multiple elements from $data. - Sorts an array by any value, determined by a Set-compatible path
Method Detail
_filter()source protected static
_filter( mixed $var )
Callback function for filtering.
Parameters
-
mixed
$var - Array to filter.
Returns
boolean_matchToken()source protected static
_matchToken( string $key , string $token )
Check a key against a token.
Parameters
-
string
$key - The key in the array being searched.
-
string
$token - The token being matched.
Returns
boolean_matches()source protected static
_matches( array|ArrayAccess $data , string $selector )
Checks whether or not $data matches the attribute patterns
Parameters
-
array|ArrayAccess
$data - Array of data to match.
-
string
$selector - The patterns to match.
Returns
booleanFitness of expression.
_merge()source protected static
_merge( array $stack , array $return )
Merge helper function to reduce duplicated code between merge() and expand().
Parameters
-
array
$stack - The stack of operations to work with.
-
array
$return - The return value to operate on.
_simpleOp()source protected static
_simpleOp( string $op , array $data , array $path , mixed $values = null )
Perform a simple insert/remove operation.
Parameters
-
string
$op - The operation to do.
-
array
$data - The data to operate on.
-
array
$path - The path to work on.
-
mixed
$valuesoptional null - The values to insert when doing inserts.
Returns
arraydata.
_splitConditions()source protected static
_splitConditions( string $token )
Split token conditions
Parameters
-
string
$token - the token being splitted.
Returns
array[token, conditions] with token splitted
_squash()source protected static
_squash( array $data , string|null $key = null )
Helper method for sort() Squashes an array to a single hash so it can be sorted.
Parameters
-
array
$data - The data to squash.
-
string|null
$keyoptional null - The key for the data.
Returns
arrayapply()source public static
apply( array $data , string $path , callable $function )
Apply a callback to a set of extracted values using $function. The function will get the extracted values as the first argument.
Example
You can easily count the results of an extract using apply(). For example to count the comments on an Article:
$count = Hash::apply($data, 'Article.Comment.{n}', 'count');
You could also use a function like array_sum to sum the results.
$total = Hash::apply($data, '{n}.Item.price', 'array_sum');
Parameters
-
array
$data - The data to reduce.
-
string
$path - The path to extract from $data.
-
callable
$function - The function to call on each extracted value.
Returns
mixedThe results of the applied method.
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::applycheck()source public static
check( array $data , string $path )
Test whether or not a given path exists in $data. This method uses the same path syntax as Hash::extract()
Checking for paths that could target more than one element will make sure that at least one matching element exists.
Parameters
-
array
$data - The data to check.
-
string
$path - The path to check for.
Returns
booleanExistence of path.
See
\Cake\Utility\Hash::extract()Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::checkcombine()source public static
combine( array $data , string $keyPath , string|null $valuePath = null , string|null $groupPath = null )
Creates an associative array using $keyPath as the path to build its keys, and optionally $valuePath as path to get the values. If $valuePath is not specified, all values will be initialized to null (useful for Hash::merge). You can optionally group the values by what is obtained when following the path specified in $groupPath.
Parameters
-
array
$data - Array from where to extract keys and values
-
string
$keyPath - A dot-separated string.
-
string|null
$valuePathoptional null - A dot-separated string.
-
string|null
$groupPathoptional null - A dot-separated string.
Returns
arrayCombined array
Throws
RuntimeExceptionWhen keys and values count is unequal.
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::combinecontains()source public static
contains( array $data , array $needle )
Determines if one array contains the exact keys and values of another.
Parameters
-
array
$data - The data to search through.
-
array
$needle - The values to file in $data
Returns
booleantrue If $data contains $needle, false otherwise
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::containsdiff()source public static
diff( array $data , array $compare )
Computes the difference between two complex arrays. This method differs from the built-in array_diff() in that it will preserve keys and work on multi-dimensional arrays.
Parameters
-
array
$data - First value
-
array
$compare - Second value
Returns
arrayReturns the key => value pairs that are not common in $data and $compare The expression for this function is ($data - $compare) + ($compare - ($data - $compare))
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::diffdimensions()source public static
dimensions( array $data )
Counts the dimensions of an array. Only considers the dimension of the first element in the array.
If you have an un-even or heterogeneous array, consider using Hash::maxDimensions() to get the dimensions of the array.
Parameters
-
array
$data - Array to count dimensions on
Returns
integerThe number of dimensions in $data
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::dimensionsexpand()source public static
expand( array $data , string $separator = '.' )
Expands a flat array to a nested array.
For example, unflattens an array that was collapsed with Hash::flatten() into a multi-dimensional array. So, ['0.Foo.Bar' => 'Far'] becomes [['Foo' => ['Bar' => 'Far']]].
Parameters
-
array
$data - Flattened array
-
string
$separatoroptional '.' - The delimiter used
Returns
arrayLink
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::expandextract()source public static
extract( array|ArrayAccess $data , string $path )
Gets the values from an array matching the $path expression. The path expression is a dot separated expression, that can contain a set of patterns and expressions:
{n}Matches any numeric key, or integer.{s}Matches any string key.{*}Matches any value.FooMatches any key with the exact same value.
There are a number of attribute operators:
=,!=Equality.>,<,>=,<=Value comparison.=/.../Regular expression pattern match.
Given a set of User array data, from a $User->find('all') call:
1.User.nameGet the name of the user at index 1.{n}.User.nameGet the name of every user in the set of users.{n}.User[id].nameGet the name of every user with an id key.{n}.User[id>=2].nameGet the name of every user with an id key greater than or equal to 2.{n}.User[username=/^paul/]Get User elements with username matching^paul.{n}.User[id=1].nameGet the Users name with id matching1.
Parameters
-
array|ArrayAccess
$data - The data to extract from.
-
string
$path - The path to extract.
Returns
array|ArrayAccessAn array of the extracted values. Returns an empty array if there are no matches.
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::extractfilter()source public static
filter( array $data , callable|array $callback = ['self', '_filter'] )
Recursively filters a data set.
Parameters
-
array
$data - Either an array to filter, or value when in callback
-
callable|array
$callbackoptional ['self', '_filter'] -
A function to filter the data with. Defaults to
static::_filter()Which strips out all non-zero empty values.
Returns
arrayFiltered array
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::filterflatten()source public static
flatten( array $data , string $separator = '.' )
Collapses a multi-dimensional array into a single dimension, using a delimited array path for each array element's key, i.e. [['Foo' => ['Bar' => 'Far']]] becomes ['0.Foo.Bar' => 'Far'].)
Parameters
-
array
$data - Array to flatten
-
string
$separatoroptional '.' - String used to separate array key elements in a path, defaults to '.'
Returns
arrayLink
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::flattenformat()source public static
format( array $data , array $paths , string $format )
Returns a formatted series of values extracted from $data, using $format as the format and $paths as the values to extract.
Usage:
$result = Hash::format($users, ['{n}.User.id', '{n}.User.name'], '%s : %s');
The $format string can use any format options that vsprintf() and sprintf() do.
Parameters
-
array
$data - Source array from which to extract the data
-
array
$paths - An array containing one or more Hash::extract()-style key paths
-
string
$format - Format string into which values will be inserted, see sprintf()
Returns
array|nullAn array of strings extracted from
$path and formatted with $formatLink
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::formatSee
sprintf()\Cake\Utility\Hash::extract()
get()source public static
get( array|ArrayAccess $data , string|array $path , mixed $default = null )
Get a single value specified by $path out of $data. Does not support the full dot notation feature set, but is faster for simple read operations.
Parameters
-
array|ArrayAccess
$data -
Array of data or object implementing \ArrayAccess interface to operate on.
-
string|array
$path -
The path being searched for. Either a dot separated string, or an array of path segments.
-
mixed
$defaultoptional null - The return value when the path does not exist
Returns
mixedThe value fetched from the array, or null.
Throws
InvalidArgumentExceptionLink
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::getinsert()source public static
insert( array $data , string $path , array|null $values = null )
Insert $values into an array with the given $path. You can use {n} and {s} elements to insert $data multiple times.
Parameters
-
array
$data - The data to insert into.
-
string
$path - The path to insert at.
-
array|null
$valuesoptional null - The values to insert.
Returns
arrayThe data with $values inserted.
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::insertmap()source public static
map( array $data , string $path , callable $function )
Map a callback across all elements in a set. Can be provided a path to only modify slices of the set.
Parameters
-
array
$data - The data to map over, and extract data out of.
-
string
$path - The path to extract for mapping over.
-
callable
$function - The function to call on each extracted value.
Returns
arrayAn array of the modified values.
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::mapmaxDimensions()source public static
maxDimensions( array $data )
Counts the dimensions of all array elements. Useful for finding the maximum number of dimensions in a mixed array.
Parameters
-
array
$data - Array to count dimensions on
Returns
integerThe maximum number of dimensions in $data
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::maxDimensionsmerge()source public static
merge( array $data , mixed $merge )
This function can be thought of as a hybrid between PHP's array_merge and array_merge_recursive.
The difference between this method and the built-in ones, is that if an array key contains another array, then Hash::merge() will behave in a recursive fashion (unlike array_merge). But it will not act recursively for keys that contain scalar values (unlike array_merge_recursive).
Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
Parameters
-
array
$data - Array to be merged
-
mixed
$merge - Array to merge with. The argument and all trailing arguments will be array cast when merged
Returns
arrayMerged array
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::mergemergeDiff()source public static
mergeDiff( array $data , array $compare )
Merges the difference between $data and $compare onto $data.
Parameters
-
array
$data - The data to append onto.
-
array
$compare - The data to compare and append onto.
Returns
arrayThe merged array.
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::mergeDiffnest()source public static
nest( array $data , array $options = [] )
Takes in a flat array and returns a nested array
Options:
childrenThe key name to use in the resultset for children.idPathThe path to a key that identifies each entry. Should be compatible with Hash::extract(). Defaults to{n}.$alias.idparentPathThe path to a key that identifies the parent of each entry. Should be compatible with Hash::extract(). Defaults to{n}.$alias.parent_idrootThe id of the desired top-most result.
Parameters
-
array
$data - The data to nest.
-
array
$optionsoptional [] - Options are:
Returns
arrayof results, nested
Throws
InvalidArgumentExceptionWhen providing invalid data.
See
\Cake\Utility\Hash::extract()Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::nestnormalize()source public static
normalize( array $data , boolean $assoc = true )
Normalizes an array, and converts it to a standard format.
Parameters
-
array
$data - List to normalize
-
boolean
$assocoptional true - If true, $data will be converted to an associative array.
Returns
arrayLink
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::normalizenumeric()source public static
numeric( array $data )
Checks to see if all the values in the array are numeric
Parameters
-
array
$data - The array to check.
Returns
booleantrue if values are numeric, false otherwise
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::numericreduce()source public static
reduce( array $data , string $path , callable $function )
Reduce a set of extracted values using $function.
Parameters
-
array
$data - The data to reduce.
-
string
$path - The path to extract from $data.
-
callable
$function - The function to call on each extracted value.
Returns
mixedThe reduced value.
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::reduceremove()source public static
remove( array $data , string $path )
Remove data matching $path from the $data array. You can use {n} and {s} to remove multiple elements from $data.
Parameters
-
array
$data - The data to operate on
-
string
$path - A path expression to use to remove.
Returns
arrayThe modified array.
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::removesort()source public static
sort( array $data , string $path , string $dir = 'asc' , array|string $type = 'regular' )
Sorts an array by any value, determined by a Set-compatible path
Sort directions
ascSort ascending.descSort descending.
Sort types
regularFor regular sorting (don't change types)numericCompare values numericallystringCompare values as stringslocaleCompare items as strings, based on the current localenaturalCompare items as strings using "natural ordering" in a human friendly way Will sort foo10 below foo2 as an example.
To do case insensitive sorting, pass the type as an array as follows:
Hash::sort($data, 'some.attribute', 'asc', ['type' => 'regular', 'ignoreCase' => true]);
When using the array form, type defaults to 'regular'. The ignoreCase option defaults to false.
Parameters
-
array
$data - An array of data to sort
-
string
$path - A Set-compatible path to the array value
-
string
$diroptional 'asc' - See directions above. Defaults to 'asc'.
-
array|string
$typeoptional 'regular' - See direction types above. Defaults to 'regular'.
Returns
arraySorted array of data
Link
https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::sort© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/3.7/class-Cake.Utility.Hash.html