Jump to content

how to print once,get out of loop and continue with rest inside same loop


shadd
Go to solution Solved by jodunno,

Recommended Posts

i have this code:

$data={"egg","york","pork"}   ;

$total=count($data);//$j=0;
    for ($i = 0; $i < $total; $i++){//$j++;
        
       
            echo 'SECTION ';
            echo ($j <= 2) ? "A" : "B" ;break;

echo $data[$i];
           }

i would like to print:

SECTION A

eggg

york

Section B

pork

....

 

how can i do that inside the for loop??How can I do  a groupby section ??

Edited by shadd
clarity
Link to comment
Share on other sites

  • Solution

if data is static and you are positive that this is the code that you wish to implement, then your logic needs to change from less than two to a more precise identifier. A switch will work better for you and allow you to adjust the code if you add more items to the array (which should not contain curly braces, rather square brackets).

<?php

$data=["egg","york","pork"];
$total = count($data);
for ($i = 0; $i < $total; $i++) {  
  switch ($i) {
    case 0: echo '<p>SECTION A<br>'; break;
    case 2: echo '</p>SECTION B<br>'; break;
  } echo $data[$i] . '<br>';
}

$data2 = (array) ['Section A' => (array) ["egg","york"], 'Section B' => (array) ["pork"]];
foreach ($data2 as $section => $array) {   
  echo '<p>' . $section . '<br>';
  foreach ($array as $type) {
    echo $type.'<br>';
  } echo '</p>';
}

?>

but i recommend that you build your arrays to structure and identify data, then looping will be easy and the resulting code will be cleaner and more logical. vide data2 array and the subsequent code above.

  • Great Answer 1
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.