Second Son Second Son - 7 months ago 18
SQL Question

Count characters and get percentage of occurrence in Php or SQL

I have a database with one table of two columns

FirstName
and
LastName

and my names are
Bruce Wayne
, so what I want is an output that will give me this:


a 1 10%
B 1 10%
c 1 10%
e 2 20%
n 1 10%
r 1 10%
u 1 10%
W 1 10%
y 1 10%


How many times each character has occurred in both names and what is the percentage of occurrence overall.
I am new to php and mysql a little help would be welcome.
Thus far I have found this http://php.net/manual/en/function.substr-count.php

$text = 'This is a test';
echo strlen($text); // 14

echo substr_count($text, 'is'); // 2


I don't know if the best approach would be php or sql. Thanks!

Answer

First split all letters in an array. Count the array. Loop through the array and count how often we see them. Then loop another time to print out the result:

<?php
$text = 'This is a test';
$text = str_replace(' ', '', $text );
$arrLetters = str_split($text);
$countLetters = count($arrLetters);

$letters = [];

foreach($arrLetters as $letter){
    if(isset($letters[$letter])){
        $letters[$letter] += 1;
    } else {
        $letters[$letter] = 1;  
    }
}

foreach($letters as $letter => $total){
    echo $letter.":".$total.":".round(($total/$countLetters*100),2)."%<br />";
}

Result:

T:1:9.09%
h:1:9.09%
i:2:18.18%
s:3:27.27%
a:1:9.09%
t:2:18.18%
e:1:9.09%