Page 1 of 1

Can't undestand...

Posted: Fri Sep 01, 2006 4:54 pm
by joaomrpereira
Hi all,

First of all, let me say that I'm very newbie in php.

Analyse this, please:


$strTest = "this is a string";

$strNeedle_one = "not";


$startPos = strpos($strTest,$strNeedle_one);

if ( $startPos >= 0 ) // allways evaluate true!!!!

This is the thing I cannot understand. If the needle is not found in the string, why this allways evaluate true?

Sorry if this is a stupid question, but I cannot undesrand it.

Thanks,

JP

Posted: Fri Sep 01, 2006 4:56 pm
by feyd
because false is always greater than or equal to zero.

Posted: Fri Sep 01, 2006 5:17 pm
by joaomrpereira
Ok, clarified.

But... still confused with the following


$strTest = "this is a string";

$strNeedle_one = "string";


$startPos = strpos($strTest,$strNeedle_one);

if ( $startPos === true ) // allways evaluate false!!!!

thanks,

Re: Can't undestand...

Posted: Fri Sep 01, 2006 5:22 pm
by Luke

Code: Select all

$startPos = strpos($strTest,$strNeedle_one);

if ( $startPos >== 0 ){}
Should give you the results you are expecting

Posted: Fri Sep 01, 2006 5:25 pm
by Luke

Code: Select all

$strTest = "this is a string";

$strNeedle_one = "string";


$startPos = strpos($strTest,$strNeedle_one);

if ( $startPos ===  true ) // allways evaluate [b]false[/b]!!!!
=== is the identical operator. true or false is not identical to any number in any case, so that will always evaluate to false since strpos returns anywhere from -1 on up.

Posted: Fri Sep 01, 2006 5:28 pm
by joaomrpereira
Thanks for the help, but :

Parse error: syntax error, unexpected '=' in ...\content.html.php on line 517


with if ( $startPos >== 0 ) {

:( :(

Posted: Fri Sep 01, 2006 5:34 pm
by joaomrpereira
The Ninja Space Goat wrote:
=== is the identical operator. true or false is not identical to any number in any case, so that will always evaluate to false since strpos returns anywhere from -1 on up.

My strpos does not return -1 when the needle is not found in the string :(

Posted: Fri Sep 01, 2006 5:38 pm
by Luke
I'm sorry I was thinking of a javscript function I think. It does return false if it can't find it:
http://fr3.php.net/manual/en/function.strpos.php

Posted: Fri Sep 01, 2006 5:42 pm
by joaomrpereira
confusing this one...

if I use:

if ( $startPos === true)

it allways return true, wheter the needle is found or not but with:

if ( $startPos !== false)

the behavior is what I expect....


strange

Posted: Fri Sep 01, 2006 5:48 pm
by feyd
strpos() does not return the boolean value true, ever. Using the identity operator to match against true will always be false. As the documentation says, use "!== false" to see if strpos() found something.

false, "", '', 0, '0' and null are all the same when using the equality based operators: >, <, >=, <=, ==, and !=.

The identity based operators check that the types match and the values match too.

Some further reading: http://php.net/language.operators.comparison