How to break foreach loop and continue

Hi guys,

I’ve an array which I want to split it two parts. How could I do it:

foreach($array as $key => $value) {
	echo $key. " has value of " . $value . ".<br/>";
	if ($key == 4) {
		echo "I'm taking a break.<br/>";
		break;
	}
	
	if ($key > 4) { # This isn't worked.
		continue;
	}
}

Thanks you,

you mean something like array_chunk() or array_splice() ?

break prematurely ends the loop, continue immediately initiates the next loop cycle. both won’t help in your case.

Thanks for reply,
Here’s the result I want:

0 has value of 0.
1 has value of 1.
2 has value of 2.
3 has value of 3.
4 has value of 4.
I'm taking a break.
5 has value of 5.
6 has value of 6.
7 has value of 7.
8 has value of 8.

I don’t know how to do this.
And array length is not fixed.

$line = '%d has a value of %s.<br>';
foreach ($array as $key => $value) {
	printf($line, $key, $value);
	if ($key === 4) {
		echo "I'm taking a break.<br>";
	}
}
1 Like

Try this:

<?php 

$array = [
'08:00 am ',
'09:00 am ',
'10:00 am',
'11:00 am',
'12:00 am',
'13:00 pm',
'14:00 pm',
'15:00 pm',
'16:00 pm',
'17:00 pm',
'18:00 pm - Overtime???',
'19:00 pm',
'20:00 pm - Still here',
'21:00 pm',
'22:00 pm - Eventually finished',
];

foreach($array as $key => $value) {

  echo '<br />#'. $key. ' &nbsp;&nbsp; => &nbsp;&nbsp; ' . $value;
  
  # break out of loop
    if ($key===9) {
      echo "&nbsp;&nbsp; Time to go home  <br/>";
      break;
    }

  switch($key) {
    case 0: $msg = 'Start work';
    break;

    case 2:
    case 7: $msg = 'Yippee, time for a coffee break.';
    break;

    case 4: $msg = 'Lunch time';
    break;

    case 5: $msg = 'Back to work';
    break;

    case 9: $msg = 'Time to go home';
    break;

    default: $msg = '...';
  }//
  echo '&nbsp;&nbsp; ' .$msg; 
}//endswitch

echo '<br /><br /><pre>$array => ', print_r($array), '</pre>';

Output:

Thanks,

Dormilich’s method work perfectly.

1 Like

it was your own code only without the break/continue.

although I’d prefer a more functional approach:

// transform array
$array = array_map(function ($key, $value) {
    return sprintf('%d has a value of %s.', $key, $value);
}, array_keys($array), $array);
// add additional line
array_splice($array, 4, 0, ['I’m taking a break.']);
// make the output the very last thing in the process:
echo implode('<br>', $array);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.