These two static functions can be dropped into any static utility class and used as getters for array values. They’ve been repurposed from Gravity Forms core code: gfar, gfars.
Example: `$user_id = absint( self::get_ars( $_POST, ‘/user/id’, 0 ) );`
<?php
/**
* Get a value from an array.
*
* @param array $array_to_check The array to get the value from.
* @param string $key The key to get the value from.
* @param mixed $default_value The default value to return if the key is not found. Default is null.
*
* @return mixed The value from the array.
*/
public static function get_ar( array $array_to_check, string $key, $default_value = null ) {
if ( ! is_array( $array_to_check ) && ! ( is_object( $array_to_check ) && $array_to_check instanceof ArrayAccess ) ) {
return $default_value;
}
if ( isset( $array_to_check[ $key ] ) ) {
$value = $array_to_check[ $key ];
} else {
$value = '';
}
return empty( $value ) && null !== $default_value ? $default_value : $value;
}
/**
* Get a value from an array by path.
*
* @param array $array_to_check The array to get the value from.
* @param string $path The path to get the value from. Can include paths separated by slashes.
* @param mixed $default_value The default value to return if the key is not found. Default is null.
*
* @return mixed The value from the array.
*/
public static function get_ars( array $array_to_check, string $path, $default_value = null ) {
if ( ! is_array( $array_to_check ) && ! ( is_object( $array_to_check ) && $array_to_check instanceof ArrayAccess ) ) {
return $default_value;
}
$names = explode( '/', $path );
$val = $array_to_check;
foreach ( $names as $current_name ) {
$val = self::get_ar( $val, $current_name, $default_value );
}
return $val;
}