Created
December 22, 2022 16:45
-
-
Save rumur/1fbfcd7ee449644d065539baa787c878 to your computer and use it in GitHub Desktop.
WordPress Array dot notation access.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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