Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

comparison - Why use !== FALSE to check stripos in php?

Here is the code I am looking at.

foreach ($header as $idx => $field) {
    if (stripos($field, 'foo') !== false) {
        $cols['foo'] = $idx;
    } else if (stripos($field, 'bar') !== false) {
        $cols['bar'] = $idx;
    } else if (stripos($field, 'brr') !== false) {
        $cols['brr'] = $idx;
    } else if (stripos($field, 'ffo') !== false) {
        $cols['ffo'] = $idx;
    }
}

Sorry, don't know how to format the code prettily either, any tips on that would be appreciated.

I am looking at some code written by someone much smarter than I, so I am not inclined to trust my first impression to just change everything to if(stripos($foo)), but why do it this way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The answer is that in PHP a "false" value can be satisfied by a handful of values, such as an empty array, an empty string, a NULL, integer 0, etc. See the empty() function page for a full list:

http://php.net/empty

So this would always yield incorrect results:

if(strpos("abc", "a")) { 
  echo "Yes";
} else {
  echo "No";
}

Since the "a" occurs at the first position (index 0) then PHP considers "if (0)" to be false.

When strpos does NOT find the needle in your haystack it will return the boolean FALSE, which is what you want to check with the triple-equal operator which checks both type and value. See the docs on comparison operators

http://www.php.net/manual/en/language.operators.comparison.php


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...