user3617651
user3617651

Reputation: 41

Why doesn't "if (strpos('a', 'a')) {" indicate that a match is found?

I've got a php while loop going (creating a search script), and I'm looking to match up values to see which items should go into the search results. strpos seems to work just fine until all of a sudden when it refuses to work correctly on this particular spot...

if (strpos('a', 'a')) {
 continue;
}

Shouldn't that NOT reach continue? "a" does contains "a" after all, but in my script it's reaching the continue.

Upvotes: 0

Views: 50

Answers (1)

Adrian Cid Almaguer
Adrian Cid Almaguer

Reputation: 7791

All is ok, just try this codes:

<?php

$value = strpos('qa', 'a');
var_dump($value);

if($value) {
 echo "inside\n<br>";
}

Output:

int(1)

inside

<?php
$value = strpos('aq', 'a');
var_dump($value);

if($value) {
 echo "inside\n<br>";
}

Output:

int(0)

In the second code $value is evaluate as false (boolean) in the typecast, because the position of a is 0 and when you evaluate 0 inside the if() the value is casting to false.

You should use this code:

if(strpos('a', 'a') === 0) {
 echo "inside\n<br>";
}

Output:

inside

You can read more at:

http://php.net/strpos

http://php.net/manual/en/language.operators.comparison.php

Upvotes: 1

Related Questions