dink87522 Posted December 30, 2009 Share Posted December 30, 2009 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? Quote Link to comment https://forums.phpfreaks.com/topic/186678-searching-string-for-entries-and-tabling-those-entries/ Share on other sites More sharing options...
Adam Posted December 30, 2009 Share Posted December 30, 2009 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); Quote Link to comment https://forums.phpfreaks.com/topic/186678-searching-string-for-entries-and-tabling-those-entries/#findComment-985888 Share on other sites More sharing options...
dink87522 Posted December 30, 2009 Author Share Posted December 30, 2009 Thanks, that got me on the right track. Quote Link to comment https://forums.phpfreaks.com/topic/186678-searching-string-for-entries-and-tabling-those-entries/#findComment-985903 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.