PHP: find the number of different letters in a string

I want to find how many unique characters a string contains. Examples:

"66615888"    contains 4 digits (6 1 5 8).
"12333333345" contains 5 digits (1 2 3 4 5).
+7
source share
5 answers
echo count( array_unique( str_split( '66615888')));

Demo

Docs:

+17
source

count_charsgives you a card char => frequencythat you can summarize with array_sum:

$count = array_sum(count_chars($str));

Alternatively, you can use the 3for mode count_chars, which will give you a string containing all the unique characters:

$count = strlen(count_chars($str, 3));
+10
source

PHP , .

$data = "foobar";
$uniqued = count_chars($data, 3);// return string(5) "abfor"
$count = strlen($uniqued);

, .

+2

script:

<?php
  $str1='66615888';
  $str2='12333333345';
  echo 'The number of unique characters in "'.$str1.'" is: '.strlen(count_chars($str1,3)).' ('.count_chars($str1,3).')'.'<br><br>';
  echo 'The number of unique characters in "'.$str2.'" is: '.strlen(count_chars($str2,3)).' ('.count_chars($str2,3).')'.'<br><br>';
?>

:

"66615888" : 4 (1568)

"12333333345" : 5 (12345)


PHP count_chars() 3 , .

The PHP string function strlen()creates the total number of unique characters.

+1
source

Here is another version that also works with multibyte strings:

echo count(array_keys(array_flip(preg_split('//u', $str, null, PREG_SPLIT_NO_EMPTY))));
0
source

All Articles