_wp_array_get() WP 5.6.0
Accesses an array in depth based on a path of keys.
It is the PHP equivalent of JavaScript's lodash.get() and mirroring it may help other components retain some symmetry between client and server implementations.
Example usage:
$array = array( 'a' => array( 'b' => array( 'c' => 1, ), ), ); _wp_array_get( $array, array( 'a', 'b', 'c' );
This is an internal function for using it by WP core itself. It's not recommended to use this function in your code.
No Hooks.
Return
Mixed
. The value from the path specified.
Usage
_wp_array_get( $array, $path, $default );
- $array(array) (required)
- An array from which we want to retrieve some information.
- $path(array) (required)
- An array of keys describing the path with which to retrieve information.
- $default(mixed)
- The return value if the path does not exist within the array, or if $array or $path are not arrays.
Changelog
Since 5.6.0 | Introduced. |
Code of _wp_array_get() wp array get WP 5.7
function _wp_array_get( $array, $path, $default = null ) {
// Confirm $path is valid.
if ( ! is_array( $path ) || 0 === count( $path ) ) {
return $default;
}
foreach ( $path as $path_element ) {
if (
! is_array( $array ) ||
( ! is_string( $path_element ) && ! is_integer( $path_element ) && ! is_null( $path_element ) ) ||
! array_key_exists( $path_element, $array )
) {
return $default;
}
$array = $array[ $path_element ];
}
return $array;
}