I’m trying to check if ALL the first string’s ($str1
) characters are in the second string ($str2
). If all of $str1
‘s characters are in $str2
, it should display “Bingo!”, if not it should display “Nope :(” .
Problem faced: My code works correctly for some examples but not for all. For instance, if both $str1
and $str2 = "jenny"
, the code displays a “Nope :(” when it should display “Bingo!” instead.
Help needed: I need help figuring out where the code has gone wrong and why this is happening. A suggested fix would be deeply appreciated.
This is a self-submitting PHP script. Input type for both $str1
and $str2
are “text”.
<?php if(!empty($_POST["send"])){ //so that code executes when submit button with the name "send" is clicked $str1 = $_POST["str1"]; $str2 = $_POST["str2"]; $ch_check = []; for($i = 0; $i <strlen($str1); $i++){ $ch = $str1[$i]; for($j = 0; $j <strlen($str2); $j++){ if($ch == $str2[$j]){ $ch_check[] = $ch; } } } //echo "<pre>"; //var_dump($ch_check); //echo "</pre>"; if(count($ch_check) == strlen($str1)){ echo "Bingo!"; }else{ echo "Nope :("; } } ?>
Advertisement
Answer
If you were to check the value of $ch_check
you would see it is an array of six characters. As a result it’s size is 6 which is not equal to the string length of “text”, which is four. This occurs because the letter “t” occurs twice in your original string so it matches twice. If you change a “t” to “c” your code works.
This is easily fixed by break
ing out of the loop once a match is made:
if($ch == $str2[$j]){ $ch_check[] = $ch; break; }
An alternative way to do this is to get all of the unique characters in both strings, find the ones they have in common, and then compare them to the characters in $str1
.
$str1 = 'text'; $str2 = 'text'; $str1chars = array_unique(str_split($str1)); $str2chars = array_unique(str_split($str2)); $matches = array_intersect($str1chars, $str2chars); if(count($str1chars) === count($matches)){ echo "Bingo!"; }else{ echo "Nope :("; }