How to count the unique characters in a string with PHP

1 Answer

0 votes
function count_unique_char($s) {
    $ascii = array_fill(0, 256, 0);
    $size = strlen($s);

    for ($i = 0; $i < $size; $i++) {
        $ascii[ord($s[$i])] = 1;
    }
 
    $count = 0;
    for ($i = 0; $i < 256; $i++) {
        $count += $ascii[$i];
        
    }
 
    return $count;
}
 
$str = "php javascript typescript node.js c c++";
 
echo count_unique_char($str);





/*
run:

18

*/

 



answered May 5, 2022 by avibootz

Related questions

...