Jump to content

Searching string for entries and tabling those entries


dink87522

Recommended Posts

I have a string that looks like "14, 1, 4, 5, 16, 17, 2, 2, 5, 1, 5, 20, 5" etc but with many more characters (and it may end up with a few thousand characters to it in the end). Each character is between 1 and 20 (inclusive) and separated by ",".

 

I need to search this string and count how many times each number occurs (i.e how many 1's, how many 2's ... how many 20's). I sort of got it working using a for loop and switch statement although it was rather obfuscated.

 

What would be the easiest way to do this?

I'd split the string by the comma and loop through each number, then create or update an array key for that number that stores the count - if that makes sense? Something like:

 

$str = '1, 1, 1, 2, 2, 7, 9, 23, 23';
$numbers = array();

foreach (explode(",", $str) as $x)
{
    $x = trim($x);

    if (!isset($numbers[$x]))
    {
        $numbers[$x] = 1;
    }
    else
    {
        $numbers[$x]++;
    }
}

print_r($numbers);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.