[Solved] Counting Characters in Text - PHP Associative Arrays

  

4
Topic starter

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

Example:

counting chars in text

2 Answers
3

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;
}
2

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;
}
Share: