'true' in Get variables
In PHP, when you have something in the URL like "var=true" in the URL, does the 'true' and 'false' in the URL get translated to boolean variables, or do they e开发者_如何学Pythonqual the text 'true' or 'false'? For instance, would, with the url having "var=false" in it:
if ($_GET['var'] == false) { ... }
work? Or would the variable always be true since it has text in it?
No, $_GET will always contain only strings.
However, you can filter it to get a boolean.
FILTER_VALIDATE_BOOLEAN:
ReturnsTRUEfor"1","true","on"and"yes". ReturnsFALSEotherwise. IfFILTER_NULL_ON_FAILUREis set,FALSEis returned only for"0","false","off","no", and"", andNULLis returned for all non-boolean values.
Example:
$value = filter_input(INPUT_GET, "varname", FILTER_VALIDATE_BOOLEAN,
array("flags" => FILTER_NULL_ON_FAILURE));
They are passed as strings, so are always truthy unless they are one of these, which evaluate to false instead:
- The empty string
'' - A string containing the digit zero
'0'
To make my life easier I just pass boolean GET variables as 1 or 0 and validate them to be either one of those values, or decide on a default value appropriately:
// Default value of false
$var = false;
if (isset($_GET['var']))
{
if ($_GET['var'] === '1' || $_GET['var'] === '0')
{
$var = (bool) $_GET['var'];
}
}
加载中,请稍侯......
精彩评论