Reputation:
I am trying to check whether a string is PANGRAM but both the codes give different results.
Number One -
<?php
$line = strtolower(trim("thequickbrownfoxjumpsoverthelazydog"));
$letters = str_split("thequickbrownfoxjumpsoverthelazydog");
$result = "pangram";
foreach ($letters as $value) {
if (strstr($line, $value) == FALSE) {
$result = "not pangram";
}
}
echo $result;
?>
Number Two -
<?php
$line = strtolower(trim("thequickbrownfoxjumpsoverthelazydog"));
$letters = str_split("thequickbrownfoxjumpsoverthelazydog");
$result = "not pangram";
foreach ($letters as $value) {
if (strstr($line, $value) == TRUE) {
$result = "pangram";
}
}
echo $result;
?>
Upvotes: 2
Views: 297
Reputation: 350
very simple panagram checking code
$string = "The quick brown fox jumps over the lazy dog";
$stringData = str_split(strtolower($string));
$check = range('a', 'z');
$res = array_intersect($check, $stringData);
if(count($check) === count($res)) echo 'panagram';
else echo 'not panagram';
thats it
Upvotes: 2
Reputation: 780889
The second version is incorrect because you can't determine that a sentence is a pangram based on checking just one character from the alphabet. So finding a matching character doesn't mean that it's a pangram. The only thing you can do is determine that a sentence is not a pangram when one of the letters in the alphabet does not exist in the test string. So you have to start with the assumption that it's a pangram, search for each letter, and when a search fails you conclude that it's not.
You can also stop looping once that happens -- one failure is enough to conclude that it's not a pangram.
foreach ($letters as $letter) {
if (!strstr($line, $letter)) {
$result = "not pangram";
break;
}
}
Upvotes: 0
Reputation: 21759
You have to use predicates, otherwise the result might change on each tick of the iteration:
$line = strtolower(trim("thequickbrownfoxjumpsoverthelazydog"));
$letters = str_split("thequickbrownfoxjumpsoverthelazydog");
$result = true;
foreach ($letters as $value) {
$result = $result && strstr($line, $value);
}
echo $result ? "pangram" : "not pangram";
With your code, if the first letter is found, the result will be TRUE
, but if the next is not found, it will be FALSE
, and, if the third is found, it will be TRUE
again, and so on...
Upvotes: 0