Search code examples
phploopsexplode

Count values with the same value inside loop


I try count elements inside loop, with the same value, as i put in my title, now i show my little script fot try to do this :

<?php
$values="1,2,3~4,5,2~7,2,9";

$expt=explode("~",$values);

foreach ($expt as $expts)
{

$expunit=explode(",",$expts);


$bb="no";

foreach($expunit as $expunits)
{

//// $expunit[1] it´s the second value in each explode

if ($expunits==="".$expunit[1]."")
{
$bb="yes";
}

if ($bb=="yes")
{
print "$expunits --- $expunit[1] ok, value it´s the same<br>";
}
else
{
print " $expunits bad, value it´s not the same<br>";
}

}

}

?>

THE SCRIPT MUST SHOW DATA IN THIS WAY :

  $values="1,2,3~4,5,2~7,2,9";

**FIRST ELEMENTS WITH THE SAME SECOND ELEMENT, IN VALUES COMMON VALUE IT´S NUMBER 2, BECAUSE IT´S IN SECOND POSITION **

FIRST :

1,2,3
7,2,9

LAST THE OTHERS

4,5,2

I try verificate the second position, between delimeters, because it´s value i want verificate for count inside loop, while explode string, actually give bad values, i think it´s bad because don´t get real or right values, i don´t know if it´s possible do it or with other script or change something in this

Thank´s Regards


Solution

  • EDIT - this is a bit closer to what you are looking for (sorry it is not perfect as I do not have time to work on it fully):

    $values="1,2,3~4,5,2~7,2,9";
    $values=explode("~",$values);
    foreach($values as $key => $expt) {
      $expit=explode(",",$expt);
      $search_value = $expit[1];
      $matched=array();
      foreach($values as $key2 => $expt2) {
        if($key !== $key2) {
          $expit2=explode(",",$expt2);
          if($expit[1]==$expit2[1]) {
            $matched[] = $expit[1];
          }
        }
      }
    }
    array_unique($matched);
    foreach($matched as $match) {
      $counter = 0;
      $no_matches = array();
      echo "<br />Matching on digit ".$match;
      foreach($values as $key3 => $expt3) {
        $expit3=explode(",",$expt3);
        if($match == $expit3[1]) {
          echo "<br />".$expt3;
          $counter++;
        } else {
          $no_matches[] = $expt3;
        }
      }
      echo "<br />Total number of matches - ".$counter;
      echo "<br />Not matching on digit ".$match;
      foreach($no_matches as $no_match) {
        echo "<br />".$no_match;
      }
    }
    

    Outputs:

    Matching on digit 2

    1,2,3

    7,2,9

    Total number of matches - 2

    Not matching on digit 2

    4,5,2