phpstringfilteringcountingnon-repetitive

Get non-repeated characters in string and count them


I need to process a string like abclkjabc and return only 3 which counts characters l, k, and j.

I've tried this.

$stringArr = [];
foreach(str_split($string) as $pwd) {
   if(!in_array($pwd, $stringArr)) {
      $stringArr[] = $pwd;
   }
}
$uniqChar = count($stringArr);

Solution

  • Try the following instead:

    function getNonRepeatingCharacters($str) {
        $counter = [];
        $spllitted = str_split($str);
        foreach($spllitted as $s) {
            if(!isset($counter[$s])) $counter[$s] = 0;
            $counter[$s]++;
        }
        $non_repeating = array_keys(array_filter($counter, function($c) {
            return $c == 1;
        }));
    
        return $non_repeating;
    }
    
    $string = "abclkjabc";
    $handle = getNonRepeatingCharacters($string);