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);
Answer
Solution:
Try the following instead:
Answer
Solution:
Functional programming and no temporary variable declarations:
array_filter()
also works but is more verbose)Code: (Demo) (or just the count)
Or with semi-functional with a loop: (Demo) (or just the count)
Output:
Getting the length of the output string can be done with
strlen()
.Instead of splitting the string and count array values, you can count character values with
count_chars()
. (Demo)Ultimately, if you only need the count of non-repeated characters, this one-liner will get you there. (Demo)
Answer
Solution:
Try this: