note 112848 deleted from function.filter-input by levim
| From: | levim@php.net | Date: | Thu, 05 Dec 2013 03:02:03 +0000 |
| Subject: | note 112848 deleted from function.filter-input by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-197741@lists.php.net to get a copy of this message | ||
Note Submitter: CertaiN
----
This function is very useful for filtering complicated array structure.
Code:
<?php
function filter_request($var, $default_structure) {
$ret = array();
foreach ($default_structure as $key => $value) {
if (!isset($var[$key])) {
$ret[$key] = $value;
} elseif (is_array($value)) {
$ret[$key] = filter_request($var[$key], $value);
} elseif (is_array($var[$key])) {
$ret[$key] = $value;
} else {
$ret[$key] = $var[$key];
}
}
return $ret;
}
?>
Sample Usage:
<?php
$_GET['a']['wrong_structure'] = 'foo';
$_GET['b']['c'] = 'CORRECT';
$_GET['b']['d']['wrong_structure'] = 'bar';
$_GET['unneeded_item'] = 'baz';
var_dump(filter_request($_GET, array(
'a' => 'DEFAULT',
'b' => array(
'c' => 'DEFAULT',
'd' => 'DEFAULT',
),
)));
?>
Sample Result:
array(2) {
["a"]=>
string(21) "DEFAULT"
["b"]=>
array(2) {
["c"]=>
string(12) "CORRECT"
["d"]=>
string(21) "DEFAULT"
}
}