1

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.

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
user3617651
  • 43
  • 1
  • 3
  • Could you show the surrounding code as this does as its intended to, and doesnt run the 'continue'.. so we'll need to see the surrounding. – Darren Aug 29 '15 at 04:46
  • It returns [the position](http://stackoverflow.com/a/4192039/3110638), which is `0`=`false`. Just use `if(strpos('a', 'a') !== false)` – Jonny 5 Aug 29 '15 at 05:05

1 Answers1

1

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

Community
  • 1
  • 1
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63