php 检查变量是否返回 true

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12518597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:42:55  来源:igfitidea点击:

Check if variable returns true

php

提问by AlxVallejo

I want to echo 'success' if the variable is true. (I originally wrote "returns true" which only applies to functions.

如果变量为真,我想回显“成功”。(我最初写的“返回真”只适用于函数。

$add_visits = add_post_meta($id, 'piwik_visits', $nb_visits, true);
if($add_visits == true){
         echo 'success';
}

Is this the equivalent of

这是否相当于

$add_visits = add_post_meta($id, 'piwik_visits', $nb_visits, true);
if($add_visits){
         echo 'success';
}

Or does $add_visits exist whether it is 'true' or 'false';

或者 $add_visits 是否存在,无论它是 'true' 还是 'false';

回答by usumoio

You might want to consider:

您可能需要考虑:

if($add_visits === TRUE){
     echo 'success';
}

This will check that your value is TRUE and of type boolean, this is more secure. As is, your code will echo success in the event that $add_visits were to come back as the string "fail" which could easily result from your DB failing out after the request is sent.

这将检查您的值是否为 TRUE 和布尔类型,这更安全。照原样,如果 $add_visits 作为字符串“fail”返回,则您的代码将回显成功,这很容易因您的数据库在发送请求后失败而导致。

回答by Guillaume Poussel

Testing $var == trueis the same than just testing $var.

测试$var == true与测试相同$var

You can read this SO questionon comparison operator. You can also read PHP manualon this topic.

您可以在比较运算符上阅读此 SO 问题。您还可以阅读有关此主题的PHP 手册

Note: a variable does not returntrue. It istrue, or it evaluatesto true. However, a function returnstrue.

注意:变量不会返回true。它true,或者它的计算结果true。但是,函数返回true.

回答by Jezen Thomas

They're the same.

他们是一样的。

This...

这个...

if ($add_visits == true)
    echo 'success';

...Is the same as:

...是相同的:

if ($add_visits)
    echo 'success';

In the same fashion, you can also test if the condition is false like this:

以同样的方式,您还可以像这样测试条件是否为假:

if (!$add_visits)
    echo "it's false!";

回答by Flemming

The most secure way is using php validation. In case of a ajax post to php:

最安全的方法是使用 php 验证。如果是 ajax post 到 php:

$isTrue=filter_var($_POST['isTrue'], FILTER_VALIDATE_BOOLEAN);

回答by Ben

Yeah, that would work fine.

是的,那会很好用。

//true
if($variable) echo "success";
if($variable == true) echo "success";


//false
if(!$variable) echo "failure";
if($variable == false) echo "failure";

回答by Dilvish5

if($add_visits === TRUE)

should do the trick.

应该做的伎俩。

回答by cdmo

if (isset($add_visits) && $add_visits === TRUE){
     echo 'success';
}

Might seem redundant, but PHP will throw a Noticeif $add_visitsisn't set. This would be the safest way to test if a variable is true.

可能看起来多余,但 PHP 会抛出一个Noticeif$add_visits未设置。这将是测试变量是否为真的最安全方法。