Jump to content

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);

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.