Reputation: 7
I want to loop every value of an array and check if it exists in another array and IF SO, delete that value from second array. And only first letter(iteration) is looped. Letter T is deleted from an array and stops looping. Please explain.
<?php
function detect_pangram($string) {
$alphas = range('A', 'Z');
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
$string = trim($string, ' ');
$array = str_split($string);
foreach($array as $value){
if(in_array($value, $alphas))
{
unset($alphas[array_search($value, $alphas)]);
continue;
}
}
var_dump($alphas);
}
detect_pangram("The quick brown fox jumps over the lazy dog.");
?>
Upvotes: 0
Views: 170
Reputation: 106375
Your foreach
loop actually works just fine (and you can witness that by prepending its body with a test echo). It's the check that fails, as in_array() doesn't (and shouldn't) care about character register:
in_array('h', range('A', 'Z')); // false
You should either transform your string to uppercase with strupper() right off the bat:
// trim is not needed, you already drop whitespace with preg_replace
$string = strtoupper(preg_replace('/[^A-Z0-9\-]/i', '', $string));
// btw, you should consider dropping all the non-A-Za-z characters, including 0-9 and -
// as their presence doesn't change the outcome of detect_pangram()
... or uppercase the letter before checking it against A...Z range.
As a sidenote, consider return true
immediately after emptying $alphas
array.
Upvotes: 2