Hi! Could we please enable some services and cookies to improve your experience and our website?
Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code
<?php
$string = 'apple banana orange apple';
function countWords(string $string) {
$clean = trim(preg_replace('/\s{2,}/', ' ', $string));
if ($clean === '') return [];
$word = '';
$counter = [];
$strlen = strlen($clean);
for ($I = 0; $I < $strlen; $I++) {
if ($clean [$I] !== ' ') $word .= $clean[$I];
if ($clean[$I] === ' ' || $strlen-1 === $I) {
if (isset($counter[$word])) $counter[$word]++;
else $counter[$word] = 1;
$word = '';
}
}
return $counter;
}
$red = countWords($string);
var_dump($res);