Damo
Damo

Reputation: 2070

PHP If Statement not working correctly, not null

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

Answers (4)

Rufinus
Rufinus

Reputation: 30721

you want to write:

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

}

Upvotes: 1

Fabrizio
Fabrizio

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

GWW
GWW

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

Marc B
Marc B

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

Related Questions