ArrayUtil::ensure_key_is_array()public staticWC 1.0

Ensure that an associative array has a given key, and if not, set the key to an empty array.

Method of the class: ArrayUtil{}

No Hooks.


true|false. True if the key has been added to the array, false if not (the key already existed).


$result = ArrayUtil::ensure_key_is_array( $array, $key, $throw_if_existing_is_not_array ): bool;
$array(array) (required)
The array to check.
$key(string) (required)
The key to check.
If true, an exception will be thrown if the key already exists in the array but the value is not an array.
Default: false

ArrayUtil::ensure_key_is_array() code WC 8.9.0

public static function ensure_key_is_array( array &$array, string $key, bool $throw_if_existing_is_not_array = false ): bool {
	if ( ! isset( $array[ $key ] ) ) {
		$array[ $key ] = array();
		return true;

	if ( $throw_if_existing_is_not_array && ! is_array( $array[ $key ] ) ) {
		$type = is_object( $array[ $key ] ) ? get_class( $array[ $key ] ) : gettype( $array[ $key ] );
		throw new \Exception( "Array key exists but it's not an array, it's a {$type}" );

	return false;