[Solved] Odd Occurrences - PHP Associative Arrays Task

  

4
Topic starter
  • Will be given sequence of words all elements that present in it odd number of times (case-insensitive).
  • Print the result elements in lowercase, in order of appearance.

Example:

odd occ php task

2 Answers
3

Here is my solution:

<?php
 
$text = array_map("strtolower", explode(" ", readline()));
$words = [];
 
foreach ($text as $currentWord) {
    if (key_exists($currentWord, $words)) {
        $words[$currentWord]++;
    } else {
        $words[$currentWord] = 1;
    }
}
 
foreach ($words as $word => $count) {
    if ($count % 2 !== 0) {
        echo $word . " ";
    }
}
2

My solution:

<?php
 
$input = array_map('strtolower', explode(' ', readline()));
$arr = [];
for ($i = 0; $i < count($input); $i++) {
    $word = $input[$i];
    if (!key_exists($word, $arr)) {
        $arr[$word] = 1;
    } else {
        $arr[$word]++;
    }
}
 
$final = [];
foreach ($arr as $key => $value) {
    if ($value % 2 !== 0) {
        $final[] = $key;
    }
}
echo implode(' ', $final);
Share: