Last active
November 13, 2020 15:22
-
-
Save Dormilich/772bd69db933ef5293a9 to your computer and use it in GitHub Desktop.
A function to apply the functionality of filter_input() to arbitrary arrays
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
/** | |
* filter_input() for arbitrary arrays. | |
* | |
* @param array $data The array to fetch the data from. | |
* @param string $name The array key of interest. | |
* @param integer $filter A filter constant | |
* @param integer|array $options Either a filter flag or an array denoting | |
* flags and/or options. | |
* @return mixed The requested value or FALSE or NULL. | |
*/ | |
function filter_array(array $data, $name, $filter = FILTER_DEFAULT, $options = NULL) | |
{ | |
if (!is_int($filter)) { | |
throw new UnexpectedValueException('Filter must be a filter constant.'); | |
} | |
$name = (string) $name; | |
if (is_null($options)) { | |
$options = $filter; | |
} | |
elseif (is_int($options)) { | |
$options |= $filter; | |
} | |
elseif (is_array($options)) { | |
$options['filter'] = $filter; | |
$options = array_intersect_key($options, array_flip(array('filter', 'flags', 'options'))); | |
} | |
$out = filter_var_array($data, [$name => $options], true); | |
return $out[$name]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment