为什么总是在这个PHP switch语句中输入案例? [关闭]

This is my code:

$array = [1,2,3];

foreach($array as $n){
  switch($n){
    case 1:
      print 1;
    case 2:
      print 2;
    default:
      print 3;
  }
}

It prints 123233

I don't get it, shouldn't it print 123 ?? I'm confused because:

  • 1 is 1, but 2 is not 1, and 3 is not 1
  • 2 is not 1, 2 is 2, 2 is not 3
  • 3 is not 1, 3 is not 2, 3 is 3

Why isn't it working as expected?

Add break after any print.

$array = [1,2,3];

foreach($array as $n){
  switch($n){
    case 1:
      print 1;
      break;
    case 2:
      print 2;
      break;
    default:
      print 3;
      break;
  }
}

If you wouldn't had a break keyword, then the code would be continue to be executed from the point of the case.