如果对数组中的任何元素验证失败,Filter_var返回false


Filter_var returns false if validating failed on any of the elements in array?

我如何使filter_var返回false如果验证失败的任何元素在数组中?

$ids = array(6,3,5,8);
$result = filter_var($ids, FILTER_VALIDATE_INT, array(
    'options' => array('min_range' => 4),
    'flags' => FILTER_REQUIRE_ARRAY
    )
);
var_dump($result);
/* returns
array(4) { [0]=> int(6) [1]=> bool(false) [2]=> int(5) [3]=> int(8) } 
*/

不幸的是,当涉及数组时,filter_var()不能返回false;您必须添加另一个条件:

if (in_array(false, $result, true)) {
    // one or more entries failed the filter
}

确保true作为in_array()的最后一个参数,否则0也会被认为是false

使用三元操作符

$result = in_array(false, $result) ? false : true;

如果数组中存在布尔值false(通过检查in_array()函数,将布尔值false赋值给$result,否则赋值给true(或返回$result)以保存数组

编辑:

对于其他数组的响应,简单地说,无论数组是否通过,都返回真或假,只需使用

$result = in_array(false, $result);