Page 1 of 1

PHP strpos() function and boolean types...

Posted: Wed Jul 21, 2004 7:12 am
by batfastad
OK I'm fairly new to PHP, basically learning as I go along but now I am stuck.

I think my understanding of comparison operators and boolean results is dodgy.

Basically I have a variable $foo in which is the string "trade magazines", or "consumer magazines"

I'm trying to have an if statement which detects whether the word "trade" is in $foo

According to the PHP documentation strpos() is the way to do this as it is less memory intensive than strstr()

I've successfully got an if statement working to check if the word "trade" isn't in $foo using === false

But how do I write the if statement to detect if "trade" is in $foo?
I've already tried the following...

Code: Select all

1) if (strpos($foo, "trade") > 0)
2) if (strpos($foo, "trade") <> false)
3) if (strpos($foo, "trade") !== false
4) if (strpos($foo, "trade") != false)
And none of them seem to work.
If any of the above are correct then let me know as it may be something else in my code throwing out the error.

What's the correct syntax to do this?
Using <> I think is incorrect as it's an arithmatic operator.
I would have thought either !== or != would work, being comparison operators but they don't seem to be.

If any of the above are correct then let me know as I'll try and track something else down in my code.

If anyone could explain how to deal with the results of functions that can either return false, or a number then let me know too so I can learn a bit more.

Thanks

Posted: Wed Jul 21, 2004 7:21 am
by markl999
!== false (or more correctly !== FALSE) should work fine.
Eg:

Code: Select all

<?php
$foo = 'trade magazines';
if (strpos($foo, "trade") !== FALSE){
  echo 'Found it';
} else {
  echo 'Not found';
}
?>

Posted: Wed Jul 21, 2004 8:01 am
by liljester
why use strpos? try strstr();

Code: Select all

$foo = "Trade Magazines";
if(strstr($foo, "trade")){
    print"found it.";
} else {
    print"not found.";
}

Posted: Wed Jul 21, 2004 8:09 am
by redmonkey
As already pointed out in the original post....
www.php.net/strstr wrote: Note: If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.

[SOLVED] PHP strpos() function and boolean types...

Posted: Wed Jul 21, 2004 9:57 am
by batfastad
Hi guys.

Just to let you know I've solved it.
Whilst trying to use the !== not identical comparison operator, I discovered the text case I was using was different to the one I was testing for.

Thanks for pointing me in the right direction.