php - Get non-repeated characters in string and count them

911

I need to process a string likeabclkjabc and return only3 which counts charactersl,k, andj.

I've tried this.

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

Answer

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);
784

Answer

Solution:

Functional programming and no temporary variable declarations:

  1. Create an array of characters
  2. Count the occurrences of each character
  3. Retain only characters that occurred once (array_filter() also works but is more verbose)
  4. Re-join the qualifying characters

Code: (Demo) (or just the count)

echo implode(
         array_keys(
             array_intersect(
                 array_count_values(
                     str_split('abclkjabc'),
                 ),
                 [1]
             )
         )
     );

Or with semi-functional with a loop: (Demo) (or just the count)

$unique = '';
foreach (array_count_values(str_split('abclkjabc')) as $char => $count) {
    if ($count === 1) {
        $unique .= $char;
    }
}
echo $unique;

Output:

lkj

Getting the length of the output string can be done withstrlen().


Instead of splitting the string and count array values, you can count character values withcount_chars(). (Demo)

$string = 'abclkjabc';
$notRepeated = [];
foreach (count_chars($string, 1) as $char => $count) {
    if ($count === 1) {
        $notRepeated[] = chr($char);
    }
}
var_export($notRepeated);
echo "\nCount = " . count($notRepeated);

Ultimately, if you only need the count of non-repeated characters, this one-liner will get you there. (Demo)

echo count(array_filter(count_chars($string, 1), fn($count) => $count === 1));
543

Answer

Solution:

Try this:

function getNonRepeatingChars($str) {
    $uniqueLetters = '';
    $multipleLetters = '';
    $arrayStr = str_split($str);

    foreach ($arrayStr as $index => $letter) {
        if (strpos($multipleLetters, $value) !== false || strpos($str, $value, $index + 1) !== false) {
            $multipleLetters .= $value;
            continue;
        }

        $uniqueLetters .= $value;
    }

    return $uniqueLetters;
}
echo getNonRepeatingChars('abclkjabc'); // lkj

People are also looking for solutions to the problem: header - Problem with PHP readfile() dumping binary data to the browser

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.