wppaste
WordPress

_wp_array_get( array $input_array, array $path, mixed $default_value = null ): mixed

Since
5.6.0
Source
wp-includes/functions.php:5069

Walks an array using a list of keys as a path and returns the value found at the end, or a fallback when any step of that path is missing. Useful when working with deeply nested configuration arrays such as theme.json data, where checking each level with isset() would be verbose. Returns the supplied default_value (null unless set) whenever input_array or path is not actually an array, so callers should not assume a non-null result means the path existed.

Accesses an array in depth based on a path of keys.

Description

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:

$input_array = array(
 'a' => array(
 'b' => array(
 'c' => 1,
 ),
 ),
);
_wp_array_get( $input_array, array( 'a', 'b', 'c' ) );

Compatibility

WordPress
since 5.6.0
PHP
7.4–8.6-dev
  • 6.7.7
  • 6.8.8
  • 6.9.7
  • 7.0.4
  • 7.1.0

Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.

Parameters

$input_arrayarray
An array from which we want to retrieve some information.
$patharray
An array of keys describing the path with which to retrieve information.
$default_valuemixedoptional
The return value if the path does not exist within the array, or if $input_array or $path are not arrays. Default null.Default: null

Return value

mixed
The value from the path specified.

Code examples

Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.

Get a nested value from a theme.json-style settings array

Core stores a lot of configuration as deeply nested arrays, so this reads one setting by its path instead of chaining isset() checks.

$theme_settings = array(
	'color' => array(
		'palette' => array(
			'custom' => array(
				array( 'slug' => 'primary', 'color' => '#0073aa' ),
			),
		),
	),
);

$custom_palette = _wp_array_get( $theme_settings, array( 'color', 'palette', 'custom' ), array() );

echo '<pre>' . esc_html( print_r( $custom_palette, true ) ) . '</pre>';

Fall back to a default when a post meta driven path is missing

Wraps a post's price meta in a nested array and shows the third argument standing in for a key that was never set.

$post_id = 2;
$price   = get_post_meta( $post_id, 'price', true );

$product_data = array(
	'pricing' => array(
		'amount' => $price,
	),
);

$currency = _wp_array_get( $product_data, array( 'pricing', 'currency' ), 'USD' );
$amount   = _wp_array_get( $product_data, array( 'pricing', 'amount' ), 0 );

echo esc_html( sprintf( 'Price: %s %s', $amount, $currency ) );

The 'currency' key was never added to $product_data, so the default 'USD' is returned for it while 'amount' comes from the real meta value.

Common problems and fixes · 4

Why does _wp_array_get() just return null instead of telling me the path was wrong?

The function has no error or warning path. Any failure, an invalid $path, a non-array $input_array partway down, or a missing key, all fall through to the same return $default_value; line, and $default_value is null unless you pass one.

Why does passing a dotted string like 'color.palette.custom' as $path not work?

The function checks is_array( $path ) before doing anything else, and returns $default_value immediately if $path is not an array, so a single string key or a dot-notation string never gets traversed.

Does it treat a key whose value is null the same as a key that isn't set?

No. The source checks with isset() first for speed, and when that fails it falls back to array_key_exists() specifically to catch keys whose stored value is null, so a real null value is returned as-is rather than being replaced by $default_value.

Can I use an object or an array as one of the path elements?

No. Inside the foreach loop, each $path_element is only accepted if it is a string, an integer, or null; anything else skips both the isset() and array_key_exists() branches and returns $default_value immediately.

Alternatives and related functions

array_key_exists
When you only need to check or read a single, shallow array key rather than walk multiple nested levels.
wp_parse_args
When you need to merge a set of caller-supplied array values with defaults rather than pull one value out of a nested structure.
get_post_meta
When the value you want lives directly on a post as meta rather than nested inside a larger array you already have in memory.

Performance profile

How much work a call to _wp_array_get() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.

Cost class
Trivial

Touches nothing outside its own arguments.

Scaling
Scales with input

The body loops, so the work grows with what you pass in.

Instructions
6–24

Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 35.

Plugin surface
None

Nothing here hands control to plugin code.

Called by
36

36 places in core call this, so the cost is paid more often than your own code shows.

What one call costs · 1 distinct outcome

One number would be a lie: the work depends on which branch runs. These are every distinct cost _wp_array_get() can have, taken from its control-flow graph on PHP 8.5.

WhenInstructionsCalls it makes
always6–24none

Across PHP versions

PHPCompiledExecutedBranchesNotes
8.6-dev376–26102 more instructions than PHP 8.5
8.5356–2410
8.4356–2410
8.3356–2410
8.2356–2410
8.1356–2410
7.4356–2410

An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.

Used by · 36

Show all 36

Source code

function _wp_array_get( $input_array, $path, $default_value = null ) {	// Confirm $path is valid.	if ( ! is_array( $path ) || 0 === count( $path ) ) {		return $default_value;	} 	foreach ( $path as $path_element ) {		if ( ! is_array( $input_array ) ) {			return $default_value;		} 		if ( is_string( $path_element )			|| is_integer( $path_element )			|| null === $path_element		) {			/*			 * Check if the path element exists in the input array.			 * We check with `isset()` first, as it is a lot faster			 * than `array_key_exists()`.			 */			if ( isset( $input_array[ $path_element ] ) ) {				$input_array = $input_array[ $path_element ];				continue;			} 			/*			 * If `isset()` returns false, we check with `array_key_exists()`,			 * which also checks for `null` values.			 */			if ( array_key_exists( $path_element, $input_array ) ) {				$input_array = $input_array[ $path_element ];				continue;			}		} 		return $default_value;	} 	return $input_array;}

Changelog

Introduced in 5.6.0. Unchanged from 6.7.7 through 7.1.0.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

About this page

Parsed data
Generated from the wordpress-develop 6.7.7 tag, from src/wp-includes/functions.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.