Fr3nch13/CakePHP Utilities

Hash
in package

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.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html

Table of Contents

Methods

apply()  : mixed
Apply a callback to a set of extracted values using `$function`.
check()  : bool
Test whether a given path exists in $data.
combine()  : array<string|int, mixed>
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`.
contains()  : bool
Determines if one array contains the exact keys and values of another.
diff()  : array<string|int, mixed>
Computes the difference between two complex arrays.
dimensions()  : int
Counts the dimensions of an array.
expand()  : array<string|int, mixed>
Expands a flat array to a nested array.
extract()  : ArrayAccess|array<string|int, mixed>
Gets the values from an array matching the $path expression.
filter()  : array<string|int, mixed>
Recursively filters a data set.
flatten()  : array<string|int, mixed>
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'].)
format()  : array<string|int, string>|null
Returns a formatted series of values extracted from `$data`, using `$format` as the format and `$paths` as the values to extract.
get()  : mixed
Get a single value specified by $path out of $data.
insert()  : array<string|int, mixed>
Insert $values into an array with the given $path. You can use `{n}` and `{s}` elements to insert $data multiple times.
map()  : array<string|int, mixed>
Map a callback across all elements in a set.
maxDimensions()  : int
Counts the dimensions of *all* array elements. Useful for finding the maximum number of dimensions in a mixed array.
merge()  : array<string|int, mixed>
This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.
mergeDiff()  : array<string|int, mixed>
Merges the difference between $data and $compare onto $data.
nest()  : array<string|int, array<string|int, mixed>>
Takes in a flat array and returns a nested array
normalize()  : array<string|int, mixed>
Normalizes an array, and converts it to a standard format.
numeric()  : bool
Checks to see if all the values in the array are numeric
reduce()  : mixed
Reduce a set of extracted values using `$function`.
remove()  : array<string|int, mixed>
Remove data matching $path from the $data array.
sort()  : array<string|int, mixed>
Sorts an array by any value, determined by a Set-compatible path
_filter()  : bool
Callback function for filtering.
_matches()  : bool
Checks whether $data matches the attribute patterns
_matchToken()  : bool
Check a key against a token.
_merge()  : void
Merge helper function to reduce duplicated code between merge() and expand().
_simpleOp()  : array<string|int, mixed>
Perform a simple insert/remove operation.
_splitConditions()  : array<string|int, mixed>
Split token conditions
_squash()  : array<string|int, mixed>
Helper method for sort() Squashes an array to a single hash so it can be sorted.

Methods

apply()

Apply a callback to a set of extracted values using `$function`.

public static apply(array<string|int, mixed> $data, string $path, callable $function) : mixed

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
$data : array<string|int, mixed>

The data to reduce.

$path : string

The path to extract from $data.

$function : callable

The function to call on each extracted value.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::apply
Return values
mixed

The results of the applied method.

check()

Test whether a given path exists in $data.

public static check(array<string|int, mixed> $data, string $path) : bool

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
$data : array<string|int, mixed>

The data to check.

$path : string

The path to check for.

Tags
see
Hash::extract()
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::check
Return values
bool

Existence of path.

combine()

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`.

public static combine(array<string|int, mixed> $data, array<string|int, string>|string|null $keyPath[, array<string|int, string>|string|null $valuePath = null ][, string|null $groupPath = null ]) : array<string|int, mixed>
Parameters
$data : array<string|int, mixed>

Array from where to extract keys and values

$keyPath : array<string|int, string>|string|null

A dot-separated string.

$valuePath : array<string|int, string>|string|null = null

A dot-separated string.

$groupPath : string|null = null

A dot-separated string.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::combine
throws
RuntimeException

When keys and values count is unequal.

Return values
array<string|int, mixed>

Combined array

contains()

Determines if one array contains the exact keys and values of another.

public static contains(array<string|int, mixed> $data, array<string|int, mixed> $needle) : bool
Parameters
$data : array<string|int, mixed>

The data to search through.

$needle : array<string|int, mixed>

The values to file in $data

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::contains
Return values
bool

true If $data contains $needle, false otherwise

diff()

Computes the difference between two complex arrays.

public static diff(array<string|int, mixed> $data, array<string|int, mixed> $compare) : array<string|int, mixed>

This method differs from the built-in array_diff() in that it will preserve keys and work on multi-dimensional arrays.

Parameters
$data : array<string|int, mixed>

First value

$compare : array<string|int, mixed>

Second value

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::diff
Return values
array<string|int, mixed>

Returns the key => value pairs that are not common in $data and $compare The expression for this function is ($data - $compare) + ($compare - ($data - $compare))

dimensions()

Counts the dimensions of an array.

public static dimensions(array<string|int, mixed> $data) : int

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
$data : array<string|int, mixed>

Array to count dimensions on

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::dimensions
Return values
int

The number of dimensions in $data

expand()

Expands a flat array to a nested array.

public static expand(array<string|int, mixed> $data[, string $separator = '.' ]) : array<string|int, mixed>

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
$data : array<string|int, mixed>

Flattened array

$separator : string = '.'

The delimiter used

Tags
phpstan-param

non-empty-string $separator

link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::expand
Return values
array<string|int, mixed>

extract()

Gets the values from an array matching the $path expression.

public static extract(ArrayAccess|array<string|int, mixed> $data, string $path) : ArrayAccess|array<string|int, mixed>

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.
  • Foo Matches 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 $usersTable->find('all') call:

  • 1.User.name Get the name of the user at index 1.
  • {n}.User.name Get the name of every user in the set of users.
  • {n}.User[id].name Get the name of every user with an id key.
  • {n}.User[id>=2].name Get 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].name Get the Users name with id matching 1.
Parameters
$data : ArrayAccess|array<string|int, mixed>

The data to extract from.

$path : string

The path to extract.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::extract
Return values
ArrayAccess|array<string|int, mixed>

An array of the extracted values. Returns an empty array if there are no matches.

filter()

Recursively filters a data set.

public static filter(array<string|int, mixed> $data[, callable|array<string|int, mixed> $callback = [Hash::class, '_filter'] ]) : array<string|int, mixed>
Parameters
$data : array<string|int, mixed>

Either an array to filter, or value when in callback

$callback : callable|array<string|int, mixed> = [Hash::class, '_filter']

A function to filter the data with. Defaults to static::_filter() Which strips out all non-zero empty values.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::filter
Return values
array<string|int, mixed>

Filtered array

flatten()

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'].)

public static flatten(array<string|int, mixed> $data[, string $separator = '.' ]) : array<string|int, mixed>
Parameters
$data : array<string|int, mixed>

Array to flatten

$separator : string = '.'

String used to separate array key elements in a path, defaults to '.'

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::flatten
Return values
array<string|int, mixed>

format()

Returns a formatted series of values extracted from `$data`, using `$format` as the format and `$paths` as the values to extract.

public static format(array<string|int, mixed> $data, array<string|int, string> $paths, string $format) : array<string|int, string>|null

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
$data : array<string|int, mixed>

Source array from which to extract the data

$paths : array<string|int, string>

An array containing one or more Hash::extract()-style key paths

$format : string

Format string into which values will be inserted, see sprintf()

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::format
see
sprintf()
see
Hash::extract()
Return values
array<string|int, string>|null

An array of strings extracted from $path and formatted with $format

get()

Get a single value specified by $path out of $data.

public static get(ArrayAccess|array<string|int, mixed> $data, array<string|int, string>|string|int|null $path[, mixed $default = null ]) : mixed

Does not support the full dot notation feature set, but is faster for simple read operations.

Parameters
$data : ArrayAccess|array<string|int, mixed>

Array of data or object implementing \ArrayAccess interface to operate on.

$path : array<string|int, string>|string|int|null

The path being searched for. Either a dot separated string, or an array of path segments.

$default : mixed = null

The return value when the path does not exist

Tags
throws
InvalidArgumentException
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::get
Return values
mixed

The value fetched from the array, or null.

insert()

Insert $values into an array with the given $path. You can use `{n}` and `{s}` elements to insert $data multiple times.

public static insert(array<string|int, mixed> $data, string $path[, mixed $values = null ]) : array<string|int, mixed>
Parameters
$data : array<string|int, mixed>

The data to insert into.

$path : string

The path to insert at.

$values : mixed = null

The values to insert.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::insert
Return values
array<string|int, mixed>

The data with $values inserted.

map()

Map a callback across all elements in a set.

public static map(array<string|int, mixed> $data, string $path, callable $function) : array<string|int, mixed>

Can be provided a path to only modify slices of the set.

Parameters
$data : array<string|int, mixed>

The data to map over, and extract data out of.

$path : string

The path to extract for mapping over.

$function : callable

The function to call on each extracted value.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::map
Return values
array<string|int, mixed>

An array of the modified values.

merge()

This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.

public static merge(array<string|int, mixed> $data, mixed $merge) : array<string|int, mixed>

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).

This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.

Parameters
$data : array<string|int, mixed>

Array to be merged

$merge : mixed

Array to merge with. The argument and all trailing arguments will be array cast when merged

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::merge
Return values
array<string|int, mixed>

Merged array

mergeDiff()

Merges the difference between $data and $compare onto $data.

public static mergeDiff(array<string|int, mixed> $data, array<string|int, mixed> $compare) : array<string|int, mixed>
Parameters
$data : array<string|int, mixed>

The data to append onto.

$compare : array<string|int, mixed>

The data to compare and append onto.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::mergeDiff
Return values
array<string|int, mixed>

The merged array.

nest()

Takes in a flat array and returns a nested array

public static nest(array<string|int, mixed> $data[, array<string, mixed> $options = [] ]) : array<string|int, array<string|int, mixed>>

Options:

  • children The key name to use in the resultset for children.
  • idPath The path to a key that identifies each entry. Should be compatible with Hash::extract(). Defaults to {n}.$alias.id
  • parentPath The path to a key that identifies the parent of each entry. Should be compatible with Hash::extract(). Defaults to {n}.$alias.parent_id
  • root The id of the desired top-most result.
Parameters
$data : array<string|int, mixed>

The data to nest.

$options : array<string, mixed> = []

Options are:

Tags
see
Hash::extract()
throws
InvalidArgumentException

When providing invalid data.

link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::nest
Return values
array<string|int, array<string|int, mixed>>

of results, nested

normalize()

Normalizes an array, and converts it to a standard format.

public static normalize(array<string|int, mixed> $data[, bool $assoc = true ]) : array<string|int, mixed>
Parameters
$data : array<string|int, mixed>

List to normalize

$assoc : bool = true

If true, $data will be converted to an associative array.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::normalize
Return values
array<string|int, mixed>

reduce()

Reduce a set of extracted values using `$function`.

public static reduce(array<string|int, mixed> $data, string $path, callable $function) : mixed
Parameters
$data : array<string|int, mixed>

The data to reduce.

$path : string

The path to extract from $data.

$function : callable

The function to call on each extracted value.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::reduce
Return values
mixed

The reduced value.

remove()

Remove data matching $path from the $data array.

public static remove(array<string|int, mixed> $data, string $path) : array<string|int, mixed>

You can use {n} and {s} to remove multiple elements from $data.

Parameters
$data : array<string|int, mixed>

The data to operate on

$path : string

A path expression to use to remove.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::remove
Return values
array<string|int, mixed>

The modified array.

sort()

Sorts an array by any value, determined by a Set-compatible path

public static sort(array<string|int, mixed> $data, string $path[, string|int $dir = 'asc' ][, array<string, mixed>|string $type = 'regular' ]) : array<string|int, mixed>

Sort directions

  • asc or \SORT_ASC Sort ascending.
  • desc or \SORT_DESC Sort descending.

Sort types

  • regular For regular sorting (don't change types)
  • numeric Compare values numerically
  • string Compare values as strings
  • locale Compare items as strings, based on the current locale
  • natural Compare 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
$data : array<string|int, mixed>

An array of data to sort

$path : string

A Set-compatible path to the array value

$dir : string|int = 'asc'

See directions above. Defaults to 'asc'.

$type : array<string, mixed>|string = 'regular'

See direction types above. Defaults to 'regular'.

Tags
link
https://book.cakephp.org/4/en/core-libraries/hash.html#Cake\Utility\Hash::sort
Return values
array<string|int, mixed>

Sorted array of data

_filter()

Callback function for filtering.

protected static _filter(mixed $var) : bool
Parameters
$var : mixed

Array to filter.

Return values
bool

_matches()

Checks whether $data matches the attribute patterns

protected static _matches(ArrayAccess|array<string|int, mixed> $data, string $selector) : bool
Parameters
$data : ArrayAccess|array<string|int, mixed>

Array of data to match.

$selector : string

The patterns to match.

Return values
bool

Fitness of expression.

_matchToken()

Check a key against a token.

protected static _matchToken(mixed $key, string $token) : bool
Parameters
$key : mixed

The key in the array being searched.

$token : string

The token being matched.

Return values
bool

_merge()

Merge helper function to reduce duplicated code between merge() and expand().

protected static _merge(array<string|int, mixed> $stack, array<string|int, mixed> &$return) : void
Parameters
$stack : array<string|int, mixed>

The stack of operations to work with.

$return : array<string|int, mixed>

The return value to operate on.

_simpleOp()

Perform a simple insert/remove operation.

protected static _simpleOp(string $op, array<string|int, mixed> $data, array<string|int, string> $path[, mixed $values = null ]) : array<string|int, mixed>
Parameters
$op : string

The operation to do.

$data : array<string|int, mixed>

The data to operate on.

$path : array<string|int, string>

The path to work on.

$values : mixed = null

The values to insert when doing inserts.

Return values
array<string|int, mixed>

data.

_splitConditions()

Split token conditions

protected static _splitConditions(string $token) : array<string|int, mixed>
Parameters
$token : string

the token being splitted.

Return values
array<string|int, mixed>

[token, conditions] with token splitted

_squash()

Helper method for sort() Squashes an array to a single hash so it can be sorted.

protected static _squash(array<string|int, mixed> $data[, mixed $key = null ]) : array<string|int, mixed>
Parameters
$data : array<string|int, mixed>

The data to squash.

$key : mixed = null

The key for the data.

Return values
array<string|int, mixed>

        
On this page

Search results