Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - strpos didn't check first word

Tags:

php

I'm trying to do some validation in PHP, and one of them is checking whether there is a specific word in the inputted string or not. The problem is, my code seem to not working when I put the specified word first.

here's the code:

$word = "aa bb cc dd";
if(strpos($word, 'aa') == false)
{
    echo "wrong input";
}

but if I change the $word to either bb aa cc dd or bb cc dd aa, it works. I wonder how to fix this though.

like image 933
aquatorrent Avatar asked May 03 '12 17:05

aquatorrent


1 Answers

strpos will return false if your string isn't there. Otherwise, it returns the position of your string.

In this case, 'aa' is at the start of the string, which means that it's at position 0; and 0 evaluates to false.

You need to do a boolean compare on the result:

if(strpos($word, 'aa') === false)
like image 83
andrewsi Avatar answered Oct 05 '22 00:10

andrewsi