为什么 strpos 第一次工作,而不是第二次?

Why is strpos working the first time, but not the second?

我正在使用 strpos 两个计时器。在第一个 if/else 中它运行良好,但在第二个中它不起作用。这是我的代码:

if (strpos($word, "mono") == true) {
    $type = "Monobloc";
} else {
    $type = "Articulated";
}

if ($word, "galva") == true) {
    $coating = "Galvanized Rod";
} elseif (strpos($word, "epoxi") == true) {
    $coating = "EPOXI 100%";
} elseif ($word, "electro") == true) {
    $coating = "Electrozinced";
}

示例: 如果变量 word 的值为 "galva-mono",则 $type 应为 "Monobloc",$coating 应为 "Galvanized Rod"。问题是它很好地分配了 $type 但在涂层中它没有进入 if 子句。

official documentation 中所述:

Warning

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

您正在使用 == true 而不是 !== false 检查结果。

所以,试试这个代码:

if (strpos($word, "mono") !== false) {
    $type = "Monobloc";
} else {
    $type = "Articulated";
}

if (strpos($word, "galva") !== false) {
    $coating = "Galvanized Rod";
} elseif (strpos($word, "epoxi") !== false) {
    $coating = "EPOXI 100%";
} elseif (strpos($word, "electro") !== false) {
    $coating = "Electrozinced";
}