PHP's strpos() not working and always getting into the if condition

試著忘記壹切 提交于 2021-01-28 05:06:43

问题


I'm trying to check if a specific character is not present in a string in my code and apparently php doesn't care about anything and always gets inside the if

foreach($inserted as $letter)
{
    if(strpos($word, $letter) !== true) //if $letter not in $word
    {
        echo "$word , $letter, ";
        $lives--;
    }
}

In this case $word is "abc" and $letter is "b", I've tried changing a lot of random things like from true to false and things like that but I can't get it, can anyone help me please?


回答1:


Changing the way you validate should fix it, like below:

     foreach($inserted as $letter)
        {
            //strpos returns false if the needle wasn't found
            if(strpos($word, $letter) === false) 
            {
                echo "$word , $letter, ";
                $lives--;
            }
        }



回答2:


if(strpos($word, $letter) === false) //if $letter not in $word
{
    echo "$word , $letter, ";
    $lives--;
}

also, be careful to check explicitly against false, strpos can return 0 (a falsey value) if the match is in the 0th index of the string...

for example

if (!strpos('word', 'w') {
    echo 'w is not in word';
}

would output the, possibly confusing, message 'w is not in word'



来源:https://stackoverflow.com/questions/54095138/phps-strpos-not-working-and-always-getting-into-the-if-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!