Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,954 questions

51,896 answers

573 users

How to count the occurrences of all the letters in a string with PHP

2 Answers

0 votes
function count_occurrences(string $s) {
    $char_occurrences = array();

    for ($i = 0; $i < strlen($s); $i++) {
        if (!isset($char_occurrences[$s[$i]])) {
            $char_occurrences[$s[$i]] = 0;
        }
        $char_occurrences[$s[$i]] ++;
    }

    return $char_occurrences;
}

$s = "php programming version 7.3.1";

$char_occurrences = count_occurrences($s);

for ($i = 0; $i < 256; $i++) {
     if (isset($char_occurrences[chr($i)])) {
         echo chr($i) . " : " . $char_occurrences[chr($i)] . "<br />";
    }
}



/*
 run:

: 3
. : 2
1 : 1
3 : 1
7 : 1
a : 1
e : 1
g : 2
h : 1
i : 2
m : 2
n : 2
o : 2
p : 3
r : 3
s : 1
v : 1

*/

 



answered Jan 30, 2019 by avibootz
0 votes
$s = "php programming version 7.3.1";

foreach (count_chars($s, 1) as $ch => $occurrences) {
   echo chr($ch) . " : " . $occurrences . "<br />";
}



/*
run:

: 3
. : 2
1 : 1
3 : 1
7 : 1
a : 1
e : 1
g : 2
h : 1
i : 2
m : 2
n : 2
o : 2
p : 3
r : 3
s : 1
v : 1

*/

 



answered Jan 30, 2019 by avibootz

Related questions

1 answer 174 views
1 answer 62 views
1 answer 137 views
1 answer 128 views
1 answer 116 views
1 answer 202 views
...