How to create an ASCII frequency table from a string in PHP

1 Answer

0 votes
function getASCIIFrequency($str) {
    $frequencyTable = array_fill(0, 128, 0);

    for ($i = 0; $i < strlen($str); $i++) {
        $frequencyTable[ord($str[$i])]++;
    }

    $accumulator = [];
    foreach ($frequencyTable as $index => $count) {
        if ($count > 0) {
            $accumulator[chr($index)] = $count;
        }
    }

    return $accumulator;
}

$str = "php javascript c c++ c# java python";

$asciiFrequency = getASCIIFrequency($str);

print_r($asciiFrequency);



/*
run:

Array
(
    [ ] => 6
    [#] => 1
    [+] => 2
    [a] => 4
    [c] => 4
    [h] => 2
    [i] => 1
    [j] => 2
    [n] => 1
    [o] => 1
    [p] => 4
    [r] => 1
    [s] => 1
    [t] => 2
    [v] => 2
    [y] => 1
)

*/

 



answered Oct 16, 2024 by avibootz

Related questions

1 answer 112 views
1 answer 115 views
1 answer 114 views
1 answer 119 views
1 answer 133 views
1 answer 107 views
...