Search code examples
phpstrpos

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


I´m using strpos two timer. In the first if/else it works well but in the second it doesn´t work. This is my code:

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";
}

Example: If the variable word has the value "galva-mono" $type should be "Monobloc" and $coating should be "Galvanized Rod". The problem is that it is assigning well the $type but in the coating it doen´t enter in the if clause.


Solution

  • As stated in the 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.

    You are checking the result with == true instead of !== false.

    So, try this code:

    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";
    }