Kris Ivanov
Kris Ivanov

Reputation: 3

PHP issue with IF statement

I am trying to check for a word in every created sting. So I am using "if" after "if" in order to check the word in every sting but also if the word is there to print out every thing in which find it. But i want if the searched word is not found in ANY of the strings to go to else statement No such word. But now the code posted "no such word" even if Only ONE of the "IFs" is not ok. Here is the code:

if(stripos($str, $text)){
  /*echo $str ;*/ echo $str = preg_replace("/\b([a-z]*${fwcode}[a-z]*)\b/i","<font color ='red'><b>$1</b></font>",$str);
    echo "</br>";   
}

if(stripos($str2, $text)){
  /*echo $str2 ;*/ echo $str2 = preg_replace("/\b([a-z]*${fwcode}[a-z]*)\b/i","<font color ='red'><b>$1</b></font>",$str2);
}

if(stripos($str3, $text)){
  /*echo $str3 ;*/ echo $str3 = preg_replace("/\b([a-z]*${fwcode}[a-z]*)\b/i","<font color ='red'><b>$1</b></font>",$str3);
}

if(stripos($str4, $text)){
  /*echo $str4 ;*/ echo $str4 = preg_replace("/\b([a-z]*${fwcode}[a-z]*)\b/i","<font color ='red'><b>$1</b></font>",$str4);
} 
    

else

{
    echo "No such word";  *** Now will print it if cannot find the $text in ANY of the $str -ings

}

$str,$str1,$str2... are the strings. $text-> is the variable for search.

Please tell me how to have all the strings checked and displayed if the searched word is there, and if in none of the is found Only Then to have else executed. Thank you.

I tried to put If statement in IF but didn't work. Please tell me how to have all the strings checked and displayed if the searched word is there, and if in none of the is found Only Then to have else executed. Thank you.

Upvotes: 0

Views: 61

Answers (1)

Valeriu Ciuca
Valeriu Ciuca

Reputation: 2094

Your else statement from your code example only applies to the last if:

$arr_string = [
    'string1',
    'string2',
    'string3',
    'string4',
];

$found = false;

foreach ($arr_string as $value) {
    if(stripos($value, $text) !== false) {
        echo preg_replace("/\b([a-z]*${fwcode}[a-z]*)\b/i","<font color ='red'><b>$1</b></font>",$value);
        $found = true;
    } 
}

if (!$found) {
    echo "No such word";
}

This way you can easily check as many strings as you want. Using a loop like foreach or for.

Also read about the use of stripos: https://www.php.net/manual/en/function.stripos.php

This function may return Boolean false, but may also return a non-Boolean value which evaluates to false.

Upvotes: 2

Related Questions