_wp_array_set( array $input_array, array $path, mixed $value = null )

In this article

This function’s access is marked private. This means it is not intended for use by plugin or theme developers, only in other core functions. It is listed here for completeness.

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

Description

It is the PHP equivalent of JavaScript’s lodash.set() and mirroring it may help other components retain some symmetry between client and server implementations.

Example usage:

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

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

Parameters

$input_arrayarrayrequired
An array that we want to mutate to include a specific value in a path.
$patharrayrequired
An array of keys describing the path that we want to mutate.
$valuemixedoptional
The value that will be set.

Default:null

Source

function _wp_array_set( &$input_array, $path, $value = null ) {
	// Confirm $input_array is valid.
	if ( ! is_array( $input_array ) ) {
		return;
	}

	// Confirm $path is valid.
	if ( ! is_array( $path ) ) {
		return;
	}

	$path_length = count( $path );

	if ( 0 === $path_length ) {
		return;
	}

	foreach ( $path as $path_element ) {
		if (
			! is_string( $path_element ) && ! is_integer( $path_element ) &&
			! is_null( $path_element )
		) {
			return;
		}
	}

	for ( $i = 0; $i < $path_length - 1; ++$i ) {
		$path_element = $path[ $i ];
		if (
			! array_key_exists( $path_element, $input_array ) ||
			! is_array( $input_array[ $path_element ] )
		) {
			$input_array[ $path_element ] = array();
		}
		$input_array = &$input_array[ $path_element ];
	}

	$input_array[ $path[ $i ] ] = $value;
}

Changelog

VersionDescription
5.8.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.