phparraysloopsstripos

Find Characters Stripost From Database Using Loop If, Elseif and Else


I have the following code:

for ($y = 0; $y <= $count_1; $y++) {
    for ($x = 0; $x <= $count_2; $x++) {
        if((strpos($cat[$y],"Model 1")!==false)and (stripos($quest[$y],$search_quest[$x])!==false) and (stripos($answ[$y],$search_answ[$x])!== false)) { 
            $ai_cat_detail ="FOUND";
        } else {
            $ai_cat_detail ="N/A";
        }
    }
    echo $ai_cat_detail."<br>";
}

Result Is:

N/A
N/A
N/A
N/A
N/A

I am expected value like this:
Found
Found
Found
N/A
N/A

And success with this code:

if((strpos($cat[$y],"Model 1")!==false)and(stripos($quest[$y],"Search Quest 1")!==false) and (stripos($answ[$y],"Search Answer 1")!== false)) {     
    $ai_cat_detail = "FOUND";
} elseif((strpos($cat[$y],"Model 1")!==false)and(stripos($quest[$y],"Search Quest 2")!==false) and (stripos($answ[$y],"Search Answer 2")!== false)){ 
    $ai_cat_detail = "FOUND";
} elseif((strpos($cat[$y],"Model 1")!==false)and (stripos($quest[$y],"Search Quest 3")!==false) and (stripos($answ[$y],"Search Answer 3")!== false)) { 
    $ai_cat_detail = "FOUND";
} elseif((strpos($cat[$y],"Model 1")!==false)and (stripos($quest[$y],"Search Quest 4")!==false) and (stripos($answ[$y],"Search Answer 4")!== false)) { 
    $ai_cat_detail = "FOUND";
} else { 
    $ai_cat_detail = "N/A";
}

So whats can i do to loop a else if and end with code else like my success code above?

Thanks for help


Solution

  • You having the wrong output as you overwrite the value of $ai_cat_detail in your loop - so the last assign is N/A is the one you echo (so it will echo FOUND only if the last if was found.

    In order to fix that export the check to function and return the string value or use break as:

    for ($y = 0; $y <= $count_1; $y++) {
        for ($x = 0; $x <= $count_2; $x++) {
            if((strpos($cat[$y],"Model 1") !== false) and (stripos($quest[$y],$search_quest[$x]) !== false) and (stripos($answ[$y],$search_answ[$x]) !== false)) { 
                $ai_cat_detail ="FOUND";
                break; // this will stop the loop if founded
            } else {
                $ai_cat_detail ="N/A";
            }
        }
        echo $ai_cat_detail."<br>";
    }
    

    Or use function as:

    function existIn($cat, $search_quest, $search_answ, $count_2, $y) {
        for ($x = 0; $x <= $count_2; $x++) {
            if((strpos($cat[$y],"Model 1") !== false) and (stripos($quest[$y],$search_quest[$x]) !== false) and (stripos($answ[$y],$search_answ[$x]) !== false)) { 
                return "FOUND";
            }
        }
        return "N/A";
    
    //use as
    for ($y = 0; $y <= $count_1; $y++) {
        echo existIn($cat, $search_quest, $search_answ, $count_2, $y) ."<br>";
    }