John Smith
John Smith

Reputation: 51

php - case-sensitive function to count how many characters in a string

I'm trying to make a function that creates an array and count how many characters are in a string, the function is case-sensitive.

I can only use foreach

example:

var_dump(count_char("H e l l o")); 
// should returns array("H" => 1, "e" => 1, "l" => 2, "o" => 1)

var_dump(count_char("Hello World"));
// should returns array("H" => 1,"W" = 1, "d" => 1, "e" => 1, "l" => 3, "o" => 2, "r" = 1)

Here is my code:

function count_char($str) {
    foreach ($str as $key => $value) {
        return strlen($value);
    }
}

Upvotes: 1

Views: 755

Answers (3)

mickmackusa
mickmackusa

Reputation: 47992

These are the steps in your task:

  1. split the string into an array of characters.
  2. filter out non-letters
  3. tally the occurrences of each letter

(There are a few ways to do this, as you can see from the answers on your next question.) Since there seems to be some stress on a foreach() loop for your assignment, I'll offer the following:

Code: (Demo)

function count_char($str) {
    $chars = str_split($str);             // split the string between each character
    $result = array();
    foreach($chars as $char) {
        if (ctype_alpha($char)) {         // only store letters
            if (!isset($result[$char])) {
                $result[$char] = 1;       // instantiate the letter in the result
            } else {
                ++$result[$char];         // increment the tally for the letter
            }
        }
    }
    return $result;
}

var_dump(count_char("Hello World"));

That said, a regular expression can perform the first two operations in one shot:

$letters = preg_split('~[^a-z]*~i', $str, -1, PREG_SPLIT_NO_EMPTY);

And as AndrewK mentions array_count_values() is a logic/direct choice:

$counts = array_count_values($letters);

Upvotes: 0

Andrew K
Andrew K

Reputation: 1

You can also use array_count_values to do the trick without looping.

$str = 'Hello World';
$str = str_replace(" ","",$str);
$chars = str_split($str);
$ret = array_count_values($chars);
print_r($ret);

Upvotes: 0

Popmedic
Popmedic

Reputation: 1871

Use an associated array and just go though the string is the easiest way...

function count_characters($str) {
    $chars = str_split($str);
    $char_counter = Array();
    foreach($chars as $char) 
        if(!isset($char_counter[$char])) $char_counter[$char] = 1;
        else $char_counter[$char] += 1;
    return $char_counter;
}

print(json_encode(count_characters("Hello World"), JSON_PRETTY_PRINT)."\n");

if you want to exclude everything but ASCII characters ([a-zA-Z]):

function count_characters($str) {
    $chars = str_split($str);
    $char_counter = Array();
    foreach($chars as $char) 
        if ((ord($char) >= 65 && ord($char) <= 90) || 
            (ord($char) >= 97 && ord($char) <= 122)) {
            if(!isset($char_counter[$char])) $char_counter[$char] = 1;
            else $char_counter[$char] += 1;
        }
    return $char_counter;
}

print(json_encode(count_characters("Hello World... test This"), JSON_PRETTY_PRINT)."\n");

To just exclude spaces:

function count_characters($str) {
    $chars = str_split($str);
    $char_counter = Array();
    foreach($chars as $char) 
        if (ord($char) != 32) {
            if(!isset($char_counter[$char])) $char_counter[$char] = 1;
            else $char_counter[$char] += 1;
        }
    return $char_counter;
}

print(json_encode(count_characters("H e l l o  W o r l d"), JSON_PRETTY_PRINT)."\n");

Upvotes: 1

Related Questions