There’s a string,
$string = ‘Foo, Bar, Test,’;
All I want to do is to count the number of the commas within a string.
But everything leads to infinite while loop.
So, I’ve tried #1:
$count = 0;
while($pos = strpos($string, ',') !== FALSE){
$count++;
// Never ends
}
And also #2,
while(true){
if ( strpos($string, ',') !== FALSE ){
$count++;
} else {
break;
}
}
They both never end. Where’s the problem?
You could just use
substr_count():In your code,
strpos()requires a third parameter to start searching from a particular offset, e.g.:It doesn’t work like an iterator. Something like this would work:
Update
If you want to get real fancy: