Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strpos not working for a certain string

Tags:

php

strpos

I'm trying to use strpos to find a string inside another string, but for some reason it isn't working for a certain string, even though it's working for the other one. What am I doing wrong?

<?php

if (strpos("show me how to dance", "show me")) {
echo "true1";
}
if (strpos("my name is name", "name")) {
echo "true2";
}

?>

Result:

true2

Expected Result:

true1true2
like image 847
frosty Avatar asked Feb 08 '23 13:02

frosty


1 Answers

strpos returns the index of the occurrence in the string (or false if it isn't found). When this index is 0, the condition: (strpos("show me how to dance", "show me")) is evaluated as false (because in PHP: 0 == false is true). To be sure the needle is found (even at index 0) you need to use a strict comparison:

if (strpos("show me how to dance", "show me") !== false)
like image 92
Casimir et Hippolyte Avatar answered Feb 10 '23 10:02

Casimir et Hippolyte