PHP过滤 - 检测过滤器故障

时间:2015-03-20 00:14:01

标签: php

更新:看来我把这个错误的部分剪掉了一个简短的例子。

在使用if(empty(0))filter_var_array时,我似乎(错误!!)使用FILTER_VALIDATE_INT来检测验证失败。

最好怎么做?

http://codepad.viper-7.com/Z8MLLj

    $positiveIntegerFilter = array('filter' => FILTER_VALIDATE_INT,
        'options' => array(
            'min_range' => 0
        )
    );

    $filter = array(
        'apples' => $positiveIntegerFilter,
        'oranges' => $positiveIntegerFilter, 
        'pears' => $positiveIntegerFilter, 
        'bananas' => $positiveIntegerFilter,
        'tangerine' => $positiveIntegerFilter
        );

    $values = Array(
        "apples" => 2,
        "oranges" => 4,
        "pears" => 0,
        "bananas" => -2, 
        "grapefruit" => 1
    );


    //Apply filter, and return only what validates
    $filteredValues = filter_var_array( $values, $filter );

    echo "values: ";
    print_r($values);
    echo "<br/>";

    echo "filteredValues: ";
    print_r($filteredValues);
    echo "<br/>";
    echo "<br/>";


    //Examine filtered array for missing parts
    foreach($filter as $key => $value) {
        echo "key = " . $key . "  // value = " . $filteredValues[$key]  . "(" . (gettype($filteredValues[$key])) .")". "<br/>" . PHP_EOL;

        if(empty($filteredValues[$key])) { //should test if(!isset()) ?
            throw new \InvalidArgumentException("Invalid information object on key: `" . $key . "`");
        }
    }

0 个答案:

没有答案