settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Counting Characters in Text - PHP Associative Arrays

+4 votes

Write a program that reads a text and counts the occurrences of each character in it.

Example:

counting chars in text

asked in PHP category by user andrew

2 Answers

+3 votes
 
Best answer

Here is my solution (with key_exists function):

<?php

$text = readline();
$output = [];

for ($i = 0; $i < strlen($text); $i++) {
    $char = $text[$i];
    if (!key_exists($char, $output)) {
        $output[$char] = 0;
    }
    $output[$char]++;
}

foreach ($output as $k => $v) {
    echo "$k -> $v" . PHP_EOL;
}
answered by user eiorgert
selected by user golearnweb
+3 votes

My answer with isset function:

<?php

$text = readline();
$occurrences = [];

for ($i = 0; $i < strlen($text); $i++) {
    if (isset($occurrences[$text[$i]])) {
        $occurrences[$text[$i]]++;
    } else {
        $occurrences[$text[$i]] = 1;
    }

}

foreach ($occurrences as $k => $v) {
    echo $k . " -> " . $v . PHP_EOL;
}
answered by user hues
...