Skip to content

Instantly share code, notes, and snippets.

@wellingguzman
Created September 16, 2014 18:22
Show Gist options
  • Save wellingguzman/ebc592f431a8f21e9023 to your computer and use it in GitHub Desktop.
Save wellingguzman/ebc592f431a8f21e9023 to your computer and use it in GitHub Desktop.
Characters Occurrences
<?php
// For "aabcd" returns "a: 2, b: 1, c: 1, d: 1"
function charOccurrences($str) {
$occurrences = [];
$len = strlen($str);
if ($len > 0) {
$chars = str_split($str);
foreach($chars as $char) {
if (array_key_exists($char, $occurrences)) {
$occurrences[$char]++;
} else {
$occurrences[$char] = 1;
}
}
}
return $occurrences;
}
$occurrences = charOccurrences("aabcd");
print_r($occurrences);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment