-1

Give an array in PHP with 100,000 string elements, I am looking for a way to count the distribution of the first character in the string.

So essentially the output I am looking for is something like:

array(
    0 => 3563,
    1 => 3146,
    ...
    'a' => 3590,
    'b' => 3863,
    ...
    'A' => 3224,
    'B' => 3765
)

How is this achieved?

Justin
  • 42,716
  • 77
  • 201
  • 296
  • It should be a straight forward loop through the array, substring and increment operation. What did you try and what problems did you run into? – Bilal Akil Oct 22 '14 at 22:00

1 Answers1

1

Iterate through with a for or foreach loop:

$distribution_count_array = array();
foreach($string_array as $item)
{
    $first_char = substr($item,0,1);
    if(isset($distribution_count_array[$first_char]))
        $distribution_count_array[$first_char] += 1;
    else
        $distribution_count_array[$first_char] = 1;
}

and keep count in a separate array, using the first letter as the key.

Alex W
  • 37,233
  • 13
  • 109
  • 109