开发者

Is there a better solution to check many variables to see if one of them is null in PHP?

On a php file that many variables are received by $_REQUEST[] or $_POST[], and I have to check them in case the value is null with the functio开发者_如何学Cn isset(), it is quite troublesome. Is there a better solution?


How about using a combination of in_array and array_map, e.g.:

// array of possible parameters that can be passed by the client
$keys = array('username','password');

// this will store the names of the ones that are not present
$missing = array();

foreach($keys as $key) {
    if(!in_array($key, $_POST)) {
        $missing[] = $key;
    }
}

$nullOffsets = array_map("is_null", $_POST);

echo 'Printing missing params:<br />';
print_r($missing);
echo 'Printing null existing params:<br />';
print_r($nullOffsets);


If you had the variables in an array (don't just use the request or post arrays) you could loop through them calling the isset() function. Depending on what your current code is, this might be 'better'.


You can try wrapping the array in an object.

class ArrayWrapper {
    private $data;
    public function __get($var) {
    if (!isset($this->data[$var])) {
        return false;
    }
    else {
        return $this->data[$var];
    }
    }
    public function __construct($a) {
    $this->data = $a;
    }
}

$a = array('test' => 1);

$aw = new ArrayWrapper($a);

if ($aw->test != false) {
    echo "test: ".$aw->test;
}
if ($aw->foo != false) {
    echo "foo: ".$aw->foo;
}


User input checking is troublesome, but its a necessary evil.

Personally I prefer not using $_GET or $_POST other than copying needed content to my own variables for processing.

At the top of my .php file, I keep an array with names of values that I wish to copy from $_GET or $_POST

This adds up to:

// the following array needs to be modified when you change your input specs
$inputAllowed = array("name", "title", "company");
$input = array();
foreach($inputAllowed as $key)
    if( array_key_exists( $key, $_POST ) )
        $input[$key] = $_POST[$key];
    else
        $input[$key] = "";

Its easy to add an "is_null" check in there with handling for in case something shouldn't be null. Or you can first let the loop finish and then loop over $input

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜