简体   繁体   中英

am I using strpos correctly? Not getting the results

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM