jlee
jlee

Reputation: 171

PHP: Find 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).

Upvotes: 11

Views: 9369

Answers (5)

Erik Kalkoken
Erik Kalkoken

Reputation: 32697

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

Upvotes: 0

merlin2011
merlin2011

Reputation: 75545

PHP has a function that counts characters.

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

Please see the documentation here.

Upvotes: 4

user8194842
user8194842

Reputation:

You can use the following 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>';
?>

Output:

The number of unique characters in "66615888" is: 4 (1568)

The number of unique characters in "12333333345" is: 5 (12345)


Here PHP string function count_chars() in mode 3 produces an array having all the unique characters.

PHP string function strlen() produces total number of unique characters present.

Upvotes: 1

NikiC
NikiC

Reputation: 101926

count_chars gives you a map of char => frequency, which you can sum up with with array_sum:

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

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

$count = strlen(count_chars($str, 3));

Upvotes: 11

nickb
nickb

Reputation: 59699

echo count( array_unique( str_split( '66615888')));

Demo

Docs:

  1. count() - Count the number of elements in an array
  2. array_unique() - Find the unique elements in an array
  3. str_split() - Split a string into an array

Upvotes: 21

Related Questions