-2

I am teaching myself PHP and have a question about IF and CASE. They seem quite similar to me, and was wondering if somebody could explain the main difference, or why/when I would use one over the other.

The example I am looking at it fairly basic - see below;

IF

if ($i == 1 ||
    $i == 2 ||
    $i == 3) {
 echo '$i is somewhere between 1 and 3.';
}

CASE

case 1:
case 2:
case 3:
    echo '$i is somewhere between 1 and 3.';
    break;

I am new to php and appreciate any advice.

jonboy
  • 2,729
  • 6
  • 37
  • 77

1 Answers1

3

From logical point of view there is not much difference, both of them are conditional branching block.

Beside that, switch statement executes faster, as it knows all the branching where the jump has to made, while for the if statement the same is not true.

consider reading . . .

  1. "if" versus "switch"
  2. Is "else if" faster than "switch() case"?
  3. If-else vs switch – Which is better?
Community
  • 1
  • 1
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110