0

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";
    }

}
5
  • 4
    strotolower(strpos()) makes no sense. strpos() returns the position as an integer, or false. Did you mean it to say strtolower($value)? Commented Jun 28, 2011 at 21:52
  • Remove strtolower and check false !== $i ;) Commented Jun 28, 2011 at 21:53
  • thanks all for your feedback. Commented Jun 28, 2011 at 22:01
  • BTW, if you want contiguous numeric keys starting at 0 (0, 1, 2, ...) in your array you can omit them: array("PaperLiBot", "TweetmemeBot", "Appsfirebot", "PycURL", "JS-Kit", "Python-urllib") Commented Jun 28, 2011 at 22:09
  • @David thanks, that'll be easier. Commented Jun 28, 2011 at 22:16

4 Answers 4

3

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";
    }

}
Sign up to request clarification or add additional context in comments.

Comments

1

you want to write:

if(stristr($value, $test)){
 // found
}else{
 // not found

}

1 Comment

That is incorrect if the position is 0 the if statement will fail.
0

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.

3 Comments

strpos returns false, not null ;)
true, but OP is explicitly checking for null for some reason.
I was looking for null by mistake. Changed to False which now works. Thanks
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.