PHP比较====问题
为什么输出是“in”?
<?php
if (1=='1, 3')
{
echo "in";
}
?>
Why is the output 'in'?
<?php
if (1=='1, 3')
{
echo "in";
}
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
==
运算符对两个值进行类型转换,尝试使它们成为相同的类型。在您的示例中,它将把第二个值从字符串转换为整数,该整数等于1
。这显然等于您匹配的值。如果您的第一个值是字符串 - 即引号中的
'1'
,而不是整数,则匹配会失败,因为两边都是字符串,因此它会进行字符串比较,并且它们是不同的字符串。如果您需要一个不进行类型转换的精确匹配运算符,PHP 还提供了一个三等号运算符
===
,它可能正是您所需要的。希望有帮助。
The
==
operator does type conversion on the two values to try to get them to be the same type. In your example it will convert the second value from a string into an integer, which will be equal to1
. This is then obviously equal to the value you're matching.If your first value had been a string - ie
'1'
in quotes, rather than an integer, then the match would have failed because both sides are strings, so it would have done a string comparison, and they're different strings.If you need an exact match operator that doesn't do type conversion, PHP also offers a tripple-equal operator,
===
, which may be what you're looking for instead.Hope that helps.
因为 PHP 正在进行类型转换,它将字符串转换为整数,并且这样做的方法可以对所有数字进行计数,直到得出非数字值。在您的情况下,这是子字符串('1')(因为
,
是第一个非数字字符)。如果字符串以数字以外的任何内容开头,则会得到 0。Because PHP is doing type conversion, it's turning a string into an integer, and it's methods of doing so work such that it counts all numbers up until a non-numeric value. In your case that's the substring ('1') (because
,
is the first non-numeric character). If you string started with anything but a number, you'd get 0.您正在比较一个字符串和一个整数。字符串必须先转换为整数,PHP 将数字字符串转换为整数。由于该字符串的开头是“1”,因此它将数字 1 与数字 1 进行比较,它们是相等的。
您想要什么功能?
You are comparing a string and an integer. The string must be converted to an integer first, and PHP converts numeric strings to integers. Since the start of that string is '1', it compares the number one, with the number one, these are equal.
What functionality did you intend?
如果你想检查 1 是否等于 1 或 3,那么我肯定会这样做:
If you're trying to check if 1 is equal to 1 or 3, then I would definitely do it this way:
请参阅 PHP 文档:
http://php.net/manual/en/ language.operators.comparison.php
Please refer to the PHP documentation:
http://php.net/manual/en/language.operators.comparison.php
输出应该是:
来自 PHP 的文档:
The output should be:
From PHP's documentation:
我猜您想知道变量是否在某个值范围内。
您可以使用
in_array
:I'm guessing you want to know whether a variable is in a range of values.
You can use
in_array
: