tags:

views:

72

answers:

4

Hi

OK I need to figure out how to count how many numbers are in the following example.

07000000000,07000000001,07000000002,07000000003,07000000004 etc...

I have tried the following PHP functions.

explode, implode, count, foreach and for.

None of them seemed to have worked and I am really stuck now.

Any help will is appriciated.

Kyle

A: 

Well, this might not be the -best- way to do it, but...

Could you just iterate for each character on the string and count the number of commas, and add 1? I mean, this requires that the string is properly formatted to be number,number,number but if you can verify that it is formatted that way, this is way to make it work.

Again, this might not be the best way (I'm not much of a php guy), there's probably better ways. But if what you're doing isn't working, maybe this will.

glowcoder
@glowcoder,I tried that at first and we are talking about arrays of maybe 10,000 values.It just didn't seem to work.
Kyle Hudson
Well, if you think about it, there's no way to tell without going through the entire array (unless you were keeping track as the array was built, of course.)If you look at it conceptually, how can you tell if you checked it all if you don't go through the entire array? Now, if that check is wrapped in a nice little function, that's great - abstract it away, awesome. But it still has to happen some time.Glad to see you found an answer!
glowcoder
+3  A: 

simple solution using explode and count:

echo count(explode(',', $string));

but you might get better performance with some regex, counting the matches, for example by using preg_match—it will return the number of matches

echo preg_match('/,/', $string);
knittl
Hi knittl,The code you suggested returns 21.+1 for the answer though
Kyle Hudson
@knittl,Thanks your first:echo count(explode(',', $string));fixed it.
Kyle Hudson
then you have 21 commas in your text
knittl
+2  A: 

Did you write your explode like this?

$array_of_numbers = explode(',', $string_of_numbers);
$count_of_numbers = count($array_of_numbers);
DexterW
Thanks Gleelmo,When i do it the method you suggested it always prints 24.
Kyle Hudson
A: 

$count = substr_count($string_of_numbers,',')+1;

Mark Baker