我无法比较 PHP 中的两个字符串
<?php
$gender = "devilcode";
if (($gender == "female") || ($gender = "male"))
{
echo "ok";
}
else echo "no";
?>
它应该输出“no”,但它输出“ok”。我做错了什么?
<?php
$gender = "devilcode";
if (($gender == "female") || ($gender = "male"))
{
echo "ok";
}
else echo "no";
?>
It should output "no" but it outputs "ok". What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您将
$gender
指定为男性,而不是测试它进行比较,您需要两个等号:You are assigning
$gender
to be male, rather than testing it for comparison, you need two equal signs:你缺少一个等号:
编辑:正是因为这个原因,许多程序员建议以相反的方式编写比较,将静态值放在左侧:
这样,如果你忘记并使用 = 而不是 ==,你会得到语法错误。
You're missing an equals sign:
Edit: For this very reason, many coders suggest writing the comparison the other way around, with the static value on the left:
This way, if you forget and use = instead of ==, you get a syntax error.
IF 的第二部分是
$gender="male"
吗?我认为这总是返回 true 并且导致了问题。设为$gender=="male"
Is the second part of the IF
$gender="male"
? I think this is returning true always and is causing the problem. Make it$gender=="male"
您的测试的第二部分存在错误。替换
为
there is a bug in the second part of your test. replace
by
编写条件的良好做法是使用反向表示法,以防止出现此类错误:
或:
Good practice for writing conditions, which protects from errors like this is using inverse notation:
or:
您将 var
$gender
分配给 'male' ($gender = 'male'
),而不是 comaring ($gender == 'male'
) code>)另外,如果您想测试几种可能的结果,请尝试
in_array()
问候。
You are assigning the var
$gender
to 'male' ($gender = 'male'
) instead of copmaring it ($gender == 'male'
)Also if you want to test against several possible outcomes try
in_array()
Regards.