如果使用filter_var_array()
密钥不存在,如何设置数组元素的默认值:
var_dump(filter_var_array([], [
"page" => [
"filter" => FILTER_VALIDATE_INT,
"options" => [
"default" => 1,
"min_range" => 0
]
]
]));
//output: [ 'page' => null ];
任何想法设置为[ 'page' => 1 ]
?
答案 0 :(得分:1)
密钥必须存在于数组中才能进行验证(通过或失败)。默认为add_empty
的第三个参数true
将缺少的密钥添加为返回值NULL
。这没有用,因为用默认值添加它会很好。
一种常见的方法是创建不存在的NULL
所需的密钥,或者最好是默认值。当$array
有共同密钥时,$required
会覆盖$array = [];
$required = ['page' => NULL]; //or 'page' => 1
$array = array_merge($required, $array);
var_dump(filter_var_array($array, [
"page" => [
"filter" => FILTER_VALIDATE_INT,
"options" => [
"default" => 1,
"min_range" => 0
]
]
]));
:
NULL
我能看到的另一种方法是将空格添加为$array = [];
var_dump($array = filter_var_array($array, [
"page" => [
"filter" => FILTER_VALIDATE_INT,
"options" => [
"default" => 1,
"min_range" => 0
]
]
]));
var_dump(filter_var_array($array, [
"page" => [
"filter" => FILTER_VALIDATE_INT,
"options" => [
"default" => 1,
"min_range" => 0
]
]
]));
,然后再次验证以获取默认值(不理想):
NULL
使用array(1) {
["page"]=>
NULL
}
值添加密钥:
array(1) {
["page"]=>
int(1)
}
添加默认值:
git diff
答案 1 :(得分:0)
我只是添加一个数组数据并且它有效
$data['page'] = NULL;
var_dump(filter_var_array($data, [
"page" => [
"filter" => FILTER_VALIDATE_INT,
"options" => [
"default" => 1,
"min_range" => 0
]
]
]));
?>