strpos 没有评估我认为应该的

strpos not evaluating to what I think it should

我在正确评估 strpos 时遇到问题。

$status = "L";
$x = strpos($status,'L');
echo var_export($x,true);
echo "<br/>";
if (strpos($status,'L') === true) {echo "L is there!.";}
else {echo "No L Found!";}

这输出:

0
No L Found!

根据我对 strpos 和“===”与“==”的理解,这应该可以找到 L。

我有什么不明白的?

strpos 不 return 为真,如果找不到字符串或找到索引,则 return 为假。

来自官方文档:

Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

你确实需要进行严格的比较。你只需要做相反的事情。

if (strpos($status, 'L') !== false) {
    echo "L is there!.";
} else {
    echo "No L Found!";
}

当用 === true 求值时,strpos($status,'L') 必须 return 一个文字布尔值 true,而不仅仅是一个求值为 true 的值,如您所见在文档中,strpos 永远不会 return 那。

如果您改用 == true,它 有时 会起作用,仅当 L 不是字符串中的第一个字符时。当它是第一个字符时,strpos($status,'L') 将 return 0,这不会计算为 true,但字符串中的任何其他位置都会 return 一个正数整数,它确实如此。

由于 false 是函数 returns 的值,如果未找到搜索字符串,执行此操作的唯一可靠方法 是严格比较 false.