PHP If 语句无法正常工作,not null
我很难理解为什么下面的 if 语句总是导致错误。我正在创建一个函数,该函数将测试与脚本的传入连接,该脚本将拒绝某些机器人建立的连接。
在下面的测试中,在应用 if 逻辑时,我期望一个 TRUE,因为数组 $value
和 $test
值都应该匹配...导致 NOT无效的?
$bots = array(0 => "PaperLiBot", 1 => "TweetmemeBot", 2 => "Appsfirebot", 3 => "PycURL", 4 => "JS-Kit", 5 => "Python-urllib");
$test = strtolower("PaperLiBot");
foreach($bots as $value)
{
$i = strtolower(strpos($value, $test));
if ($i != NULL)
{
echo "Bot is found";
exit;
}else
{
echo "not found";
}
}
I'm struggling to understand why my if statement below always results in false. I am creating a function which will test incoming connections to a script which will reject connections made by certain bots.
In my test below, on applying the if logic, I'm expecting a TRUE as both the array $value
and $test
value should match... resulting in a NOT NULL?
$bots = array(0 => "PaperLiBot", 1 => "TweetmemeBot", 2 => "Appsfirebot", 3 => "PycURL", 4 => "JS-Kit", 5 => "Python-urllib");
$test = strtolower("PaperLiBot");
foreach($bots as $value)
{
$i = strtolower(strpos($value, $test));
if ($i != NULL)
{
echo "Bot is found";
exit;
}else
{
echo "not found";
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为你正在努力实现这个目标
I think you are trying to accomplish this
你想写:
you want to write:
PHP 中的 null 可以相互类型转换为 '0'、''、' ' 等...您需要使用严格比较来检查基于 0 的数组索引:
注意额外的
=
在不等式运算符中。它强制 PHP 比较类型和值,而不仅仅是值。当比较值时,PHP 会根据需要进行类型转换以使测试正常进行,这意味着null == 0
为 true,但null === 0
为 false 。null in PHP is mutually type-castable to '0', '', ' ', etc... You need to use the strict comparisons to check for a 0-based array index:
note the extra
=
in the inequality operator. It forces PHP to compare type AND value, not just value. When comparing value, PHP will typecast however it wants to in order to make the test work, which meansnull == 0
is true, butnull === 0
is false.检查变量是否设置为 NULL 的正确方法是:
strpos 返回布尔值,而不是 NULL 值。
如果您不确定变量的内容,您始终可以使用简单的方法对其进行调试
the correct way to check if a variable is set to NULL is:
the strpos returns a boolean, not a NULL value.
if you are unsure of the content of a variable, you can always debug it with a simple