Mage2 Beginner
Mage2 Beginner

Reputation: 53

Text for every first element on specific value foreach loop PHP

I have an array like below but what I want expected output is also printed first in this code. I have tried the code below as well but the issue is it is going every time in the loop but not print what I want. Can anyone please guide me over here.

Help would be much much appreciated.

Zero Text Printing 
0
0
0
0
0
One Text Printing
1
1
1
1
1
1
1
Two Text Printing
2
2
2
2
2
2
2
2
2
2
2

 $array = [0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2];
    
    $zeroText = true;
    $oneText = true;
    $twoText = true;
      
      foreach($array as $value){
      if($zeroText){
            echo 'zero Text Printing';
            echo '<br>';
            $zeroText = false;
        }
        if($oneText){
            echo 'one Text Printing';
            echo '<br>';
            $oneText = false;
        }
        if($twoText){
            echo 'two Text Printing';
            echo '<br>';
            $twoText = false;
        }
        echo $value;
    }

Upvotes: 0

Views: 384

Answers (1)

C3roe
C3roe

Reputation: 96316

What you want, is called a control break. You compare the relevant property of your current loop item, with that of the previous one - and based on whether they are the same or not, you decide what to do.

Put your header texts into an array, so that their index in there corresponds with the values you got in your data array, then you can simply use that value to access the correct header.

$header = ['Zero Text Printing', 'One Text Printing', 'Two Text Printing'];

$array = [0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2];

$previous_value = -1;

foreach($array as $item) {
  if($previous_value != $item) {
    echo $header[$item] . '<br>';
  }
  echo $item . '<br>';
  $previous_value = $item;
}

Upvotes: 1

Related Questions