Problem with foreach() printing twice

Asked

Viewed 60 times

0

I have the following code:

$ms = [8,12,13];

// $ms = json_decode($ar,true); // sobrou da versão anterior da pergunta

for($i=1; $i<21; $i++)
{
   foreach($ms as $obj){ 
      if( $i == $obj ) { 
         echo $obj;
      }
   } 
   echo $i; 
}

I need to take the array() and continue without duplication.

  • Output: 1 2 3 4 5 6 7 8 8 9 10 11 12 12 13 13 14 15 16 17 18 19 20

  • Expected: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Turns out, if I take the stretch

foreach($ms as $r){ 
   if( $i == $obj ) { 
      echo ....
   }
}

I get the desired result, but I need to take the value of the array and apply some Tyles if the value is found.

  • 2

    You want one thing and ask another. I explained in the answer the duplication of where it comes from. If the goal was just to format differently, you should have put the question (and the solution would be completely different from your loop and even simpler). That’s what we call Problemaxy. I tried to take advantage of the code and updated the answer, but I recommend reading the link to the next.

  • 3

    The question is not about PHP7 specifically, nothing in the question contains anything related to PHP7 functionalities/Features, everything described works since php5.4, so the tag should not even be PHP-7, it should be ONLY [PHP] ... PS: the last edit of the question makes no sense, a truth array inside PHP cannot be decoded again with json_decode, only strings containing json can, this code will not even run, the $ms will be null, obtained warning: PHP Warning: json_decode() expects parameter 1 to be string, array given

1 answer

3

The code is printing twice the amount as expected.

Once in the echo $r['status'], and another in the echo $i;

As you commented that you will use for formatting, you probably want it to print an echo or other. So, to prevent the echo outside be printed, can use the continue within the if. The 2 means that it will iterate the 2nd loop, not just the inside:

$ar = [8,12,13];

for( $i = 1; $i < 21; $i++) {
   foreach($ar as $obj) { 
      if( $i == $obj ) { 
         echo '<b>'.$i.'</b> ';
         continue 2; // Já imprimiu, entao itera o loop sem passar
                     // pelo echo seguinte.
      }
   } 
   echo $i.' '; 
}

See working online on IDEONE.

Handbook: continue

  • Perfect, thanks for the attention! I understand the operation of 'continue'.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.