Skip to content

Instantly share code, notes, and snippets.

@rumur
Created December 22, 2022 16:45
Show Gist options
  • Save rumur/1fbfcd7ee449644d065539baa787c878 to your computer and use it in GitHub Desktop.
Save rumur/1fbfcd7ee449644d065539baa787c878 to your computer and use it in GitHub Desktop.
WordPress Array dot notation access.
<?php
/**
* Class Arr.
*/
class Arr {
/**
* Get an item from an array using `dot.key.notation`.
*
* @param array $array Target array.
* @param string $key The key we need to check against.
* @param mixed $default The default value in case there is nothing been found.
*
* @return mixed
*/
public static function get( array $array, string $key, $default = null ) {
return _wp_array_get( $array, static::dot_key_to_path( $key ), $default );
}
/**
* Get an item from an array using "dot" notation.
*
* @param array $array Target array.
* @param string $key The key we need to check against.
* @param mixed $value The value that will be set.
*
* @return void
*/
public static function set( array &$array, string $key, $value ): void {
_wp_array_set( $array, static::dot_key_to_path( $key ), $value );
}
/**
* Prepares the dot keys into the array path.
*
* @param string $key The dot key e.g. `a.b.c.1`.
*
* @return string[]
*/
protected static function dot_key_to_path( string $key ): array {
return explode( '.', $key );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment