4
19/10/2024 9:58 am
Argomento iniziale
Write a program that reads a text and counts the occurrences of each character in it.
Example:

2 risposte
3
19/10/2024 9:59 am
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
19/10/2024 10:00 am
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;
}
