Test if string could be boolean PHP

后端 未结 8 2198
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-20 17:51

I\'m getting a string from a $_GET and I want to test if it could be a boolean, before I use it for a part of a mysql query. Is there a better way of doing it than:



        
8条回答
  •  孤独总比滥情好
    2021-02-20 18:21

    Boolean variables contain true or false values. To test if string could be boolean, different approaches can be used:

    • is_bool($var): The function is_bool() checks whether a variable’s type is Boolean and returns true or false.

    • Comparison using “===” or ($var===true || $var===false): If you compare the variable with the operator “===” with true and false and if it is identical to one of the values, then it is a boolean value. Since the functionality of is_bool($var) is same, the function should be preferred.

    • Comparison using “==” or ($var == true || $var == false): If you use “==” as an operator instead, the test is more tolerant. For example, 0(integer) or “”(empty string) would also result in a Boolean value.

    Read more in How to check if a variable is a Boolean in PHP?

提交回复
热议问题