felix cheruiyot
felix cheruiyot

Reputation: 311

PHP: Counting elements using for loops

I would like to count numeric values in a group of two for equal values. For example for list of values 1,2,3,3,3,3,3,3,3,3,5,5,6

I should have 1,2,(3,3),(3,3),(3,3),(3,3),(5,5),6

That is when I decide to count the first (3,3) are counted as 1. Therefore in this case I should have $count=8 instead of $count=13 for all values. I have tried to do some for loops and if statements but I get wrong results. Any idea is highly appreciated. Thanks

Note: the pairs have to be adjacent to be regarded as 1.

Upvotes: 2

Views: 156

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173542

Regular expression solution with back references:

$s = '1,2,3,3,3,3,3,3,3,3,5,5,6';

echo count(explode(',', preg_replace('/(\d+),\\1/', '\\1', $s)));

Output:

8

The regular expression matches a number and then uses a back reference to match the number adjacent to it. When both are matched, they are replaced by one number. The intermediate result after the preg_replace is:

1,2,3,3,3,3,5,6

After that, the count is performed on the comma separated values.

Upvotes: 3

Scuzzy
Scuzzy

Reputation: 12332

$list = array(1,2,3,3,3,3,3,3,3,3,5,5,6);
$counter = 0;
foreach($list as $number)
{
  if(isset($previous) and $previous === $number)
  {
    unset($previous);
  }
  else
  {
    $previous = $number;
    $counter++;
  }
}
echo $counter; // 8

Upvotes: 4

Related Questions