Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

As part of studying algorithms, I needed to make a function to count occurrences of characters in a string. My solution is below. I'd like some feedback about how I did - could the implementation be cleaner? Are there any conceptual gaps my code suggests?

<?php
function ra_count_chars($str){
    $dict = str_split(strtolower(str_replace(' ', '', $str)));

    foreach($dict as $key=>$value){
        $dict[$value] = 0;
        unset($dict[$key]);
    }

    for($i = 0; $i < strlen($str); $i++){
        $dict[$str[$i]] += 1;
    }

    return $dict;
}

print_r(ra_count_chars('ccaaat'));
share|improve this question
up vote 1 down vote accepted

You can achieve your goal with only one loop. I also find it easier to understand and to maintain if you have two variables instead of just one. Unsetting the numeric keys while filling associative keys could get tricky at some point.

function ra_count_chars($str) {
    $dict = [];
    $chars = str_split(strtolower(str_replace(' ', '', $str)));

    foreach ($chars as $char) {
        isset($dict[$char]) ? ++$dict[$char] : $dict[$char] = 1;
    }

    return $dict;
}

It simply checks whether the character is already in the dictionary:

  • if no, it's set
  • if yes, its count is increased.

Keep in mind that this does not work for multi-byte characters.


Yes, this is PHP and so this would work, too: foreach ($chars as $char) { ++$dict[$char]; }. But you should always check array values beforehand to not raise a PHP: Notice.

share|improve this answer

You can do it with a more reduced code, taking advantage of the PHP count_chars() function:

function ra_count_chars($str) {
    foreach (count_chars(str_replace(' ', '', $str), 1) as $char => $count) {
        $result[chr($char)] = $count;
    }
    return $result;
}

This method has pros and cons:

  • pro: the characters are alphabetically sorted in $result
  • pro or con (depends on your need): upper- and lower-case are counted separately

In the other hand, as noticed by @insertusernamehere, this doesn't work for multibyte characters.

Last point: due to the above limitation, you might choose to omit not only spaces but also any character other than A-Z and a-z.
To achieve it merely change str_replace(' ', '', $str) into preg_replace('/[^A-za-z]/', '', $str).

share|improve this answer
    
Today I learnt something. Didn't know that a function count_chars exists. – insertusernamehere yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.