Strpos () inside while loop never ends
There is a line
$ string = 'Foo, Bar, Test,';
All I want to do is count the number of commas inside the string.
But everything leads to an endless while loop.
So I tried # 1:
$ count = 0;
while($pos = strpos($string, ',') !== FALSE){
$count++;
// Never ends
}
And also # 2,
while(true){
if ( strpos($string, ',') !== FALSE ){
$count++;
} else {
break;
}
}
Both of them never end. Where is the problem?
source to share
You can simply use substr_count()
:
substr_count($string, ',');
Your code strpos()
requires a third parameter to start the search at a specific offset, for example:
strpos($string, ',', 12); // start searching from index 12
It doesn't work like an iterator. Something like this will work:
$start = 0;
while (($pos = strpos($string, ',', $start)) !== FALSE) {
$count++;
$start = $pos + 1;
}
Update
If you want some real fantasy:
class IndexOfIterator implements Iterator
{
private $haystack;
private $needle;
private $start;
private $pos;
private $len;
private $key;
public function __construct($haystack, $needle, $start = 0)
{
$this->haystack = $haystack;
$this->needle = $needle;
$this->start = $start;
}
public function rewind()
{
$this->search($this->start);
$this->key = 0;
}
public function valid()
{
return $this->pos !== false;
}
public function next()
{
$this->search($this->pos + 1);
++$this->key;
}
public function current()
{
return $this->pos;
}
public function key()
{
return $this->key;
}
private function search($pos)
{
$this->pos = strpos($this->haystack, $this->needle, $pos);
}
}
foreach (new IndexOfIterator($string, ',') as $match) {
var_dump($match);
}
source to share
strpos()
returns the first occurrence $needle
, so if you don't specify another $offset
, you always get the same result, thus an infinite loop.
If you insist on using strpos()
, try this:
$pos=0;
while(($pos = strpos($string, ',',$pos)) !== FALSE){
$count++;
$pos++;
// This ends
}
You can use substr_count()
to simplify the task.
Edit
source to share