_wp_array_get( array $input_array, array $path, mixed $default_value = null ): mixed
- Since
- 5.6.0
- Source
wp-includes/functions.php:5084
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.
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_arrayor$pathare 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?
- Why does passing a dotted string like 'color.palette.custom' as $path not work?
- Does it treat a key whose value is null the same as a key that isn't set?
- Can I use an object or an array as one of the path elements?
Why does _wp_array_get() just return null instead of telling me the path was wrong?
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?
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?
Can I use an object or an array as one of the path elements?
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
- Light
- Scaling
- Scales with input
- Instructions
- 6–28
- Plugin surface
- None
- Called by
- 36
Touches nothing outside its own arguments.
The body loops, so the work grows with what you pass in.
Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 39.
Nothing here hands control to plugin code.
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.
| When | Instructions | Calls it makes |
|---|---|---|
| always | 6–28 | none |
Across PHP versions
| PHP | Compiled | Executed | Branches | Notes |
|---|---|---|---|---|
| 8.6-dev | 41 | 6–30 | 12 | 2 more instructions than PHP 8.5 |
| 8.5 | 39 | 6–28 | 12 | |
| 8.4 | 39 | 6–28 | 12 | |
| 8.3 | 39 | 6–28 | 12 | |
| 8.2 | 39 | 6–28 | 12 | |
| 8.1 | 39 | 6–28 | 12 | |
| 7.4 | 39 | 6–28 | 12 |
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
- WP_Duotone::get_all_global_style_block_names()Scrape all block names from global styles and store in self::$global_styles_block_names.
- WP_Style_Engine::get_individual_property_css_declarations()Style value parser that returns a CSS definition array comprising style properties that have keys representing individual style properties, otherwise known as longhand CSS properties.
- WP_Style_Engine::parse_block_styles()Returns classnames and CSS based on the values in a styles object.
- WP_Theme_JSON::__construct()Constructor.
- WP_Theme_JSON::compute_style_properties()Given a styles array, it extracts the style properties and adds them to the $declarations array following the format:
- WP_Theme_JSON::do_opt_in_into_settings()Enables some settings.
- WP_Theme_JSON::get_css_variables()Converts each styles section into a list of rulesets to be appended to the stylesheet.
- WP_Theme_JSON::get_data()Returns a valid theme.json as provided by a theme.
- WP_Theme_JSON::get_default_slugs()Returns the default slugs for all the presets in an associative array whose keys are the preset paths and the leaves is the list of slugs.
- WP_Theme_JSON::get_layout_styles()Gets the CSS layout rules for a particular block from theme.json layout definitions.
- WP_Theme_JSON::get_metadata_boolean()For metadata values that can either be booleans or paths to booleans, gets the value.
- WP_Theme_JSON::get_name_from_defaults()Gets a `default`'s preset name by a provided slug.
Show all 36
- WP_Theme_JSON::get_preset_classes()Creates new rulesets as classes for each preset value such as:
- WP_Theme_JSON::get_property_value()Returns the style property for the given path.
- WP_Theme_JSON::get_settings_slugs()Similar to get_settings_values_by_slug, but doesn't compute the value.
- WP_Theme_JSON::get_settings_values_by_slug()Gets preset values keyed by slugs based on settings and metadata.
- WP_Theme_JSON::get_styles_for_block()Gets the CSS rules for a particular block from theme.json.
- WP_Theme_JSON::get_stylesheet()Returns the stylesheet that results of processing the theme.json structure this object represents.
- WP_Theme_JSON::get_svg_filters()Converts all filter (duotone) presets into SVGs.
- WP_Theme_JSON::merge()Merges new incoming data.
- WP_Theme_JSON::remove_indirect_properties()Removes indirect properties from the given input node and sets in the given output node.
- WP_Theme_JSON::remove_insecure_properties()Removes insecure data from theme.json.
- WP_Theme_JSON::remove_insecure_settings()Processes a setting node and returns the same node without the insecure settings.
- WP_Theme_JSON::remove_insecure_styles()Processes a style node and returns the same node without the insecure styles.
- WP_Theme_JSON::should_override_preset()Determines whether a presets should be overridden or not.
- WP_Theme_JSON_Schema::rename_settings()Processes a settings array, renaming or moving properties.
- _block_bindings_pattern_overrides_get_value()Gets value for the Pattern Overrides source.
- apply_block_core_search_border_style()This generates a CSS rule for the given border property and side if provided.
- block_has_support()Checks whether the current block type supports the feature requested.
- wp_get_block_css_selector()Determines the CSS selector for the block type and property provided, returning it if available.
- wp_get_global_settings()Gets the settings resulting of merging core, theme, and user data.
- wp_get_global_styles()Gets the styles resulting of merging core, theme, and user data.
- wp_resolve_block_style_variation_ref_values()Recursively resolves any `ref` values within a block style variation's data.
- wp_should_add_elements_class_name()Determines whether an elements class name should be added to the block.
- wp_should_skip_block_supports_serialization()Checks whether serialization of the current block's supported properties should occur.
- wp_typography_get_css_variable_inline_style()Generates an inline style for a typography feature e.g. text decoration, text transform, and font style.
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( $path_element, $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 ( isset( $path_element ) && 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.
Signature, return type and hooks compared across 5 parsed releases.
About this page
- Parsed data
- Generated from the wordpress-develop 6.9.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.