Reputation: 2070
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";
}
}
Upvotes: 0
Views: 3044
Reputation: 30721
you want to write:
if(stristr($value, $test)){
// found
}else{
// not found
}
Upvotes: 1
Reputation: 3776
the correct way to check if a variable is set to NULL is:
if(!is_null($var)){
[my code]
}
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
var_dump($var);
Upvotes: 0
Reputation: 44093
I think you are trying to accomplish this
foreach($bots as $value)
{
$i = strpos(strtolower($value), $test);
if ($i !== false){
echo "Bot is found";
exit;
}else{
echo "not found";
}
}
Upvotes: 3
Reputation: 360592
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:
if ($i !== NULL) {
...
}
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 means null == 0
is true, but null === 0
is false.
Upvotes: 0