PHP if ( $some_var == 1 ) always returns true even if it's not true?

拟墨画扇 提交于 2019-12-23 11:36:47

问题


This issue is simple, but I am not sure what is the best approach to get around it.

If the variable contains a number, how can I make sure that the if statement only returns true if indeed the $some_var is one?


回答1:


you need to use 3 equals

if($some_var ===1){

here is more info http://php.net/manual/en/language.operators.comparison.php




回答2:


The number 1 is a shortcut for "true". In order to specify that it must actually be true, you want to use a triple equals operator. This makes sure it matches both value and type (1 and integer, respectively).

$some_var = 1;
$other_var = "1";

$some_var === 1; // True
$other_var === 1; // False



回答3:


if($some_var === 1) //checks also type



回答4:


Ideally, you should be using ===, but the downside of that is its going to check for both value and type. This should be fine if you want to check for 1 as an integer. But since 1 could also be a string value (data submitted by forms are always strings), your === comparison might fail. Try this instead:

if ($my_var == 1 && is_numeric($my_var)) {

    echo 'My condition is true. Woo hoo!';
}


来源:https://stackoverflow.com/questions/8188749/php-if-some-var-1-always-returns-true-even-if-its-not-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!