简体   繁体   中英

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

How can I make filter_var to return false if validating failed on any of the elements in array?

$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) } 
*/

Unfortunately, filter_var() can't be made to return false when arrays are involved; you'd have to add another condition:

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

Make sure to have true as the last argument to in_array() , otherwise 0 would also be considered false .

Use a ternary operator:

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

If boolean false is in your array (by checking with the in_array() function, assign boolean false to $result, otherwise assign true (or return the $result) to save the array.

Edit:

In response to others, in shorthand, to return true or false, whether the array has passed or not, simply use

$result = in_array(false, $result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM