0

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.");
?>
1
  • T is the only uppercase letter. Commented Jul 3, 2021 at 11:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.