# PHP if else if vs case switch vs nested if speed

A PHP if, else if vs case switch vs nested if speed test comparison from Jeff-Russ found here.

The test is a loop that calculates with a high number (500,000) in the end finding the remainder from the modulus of 16. The timing is done with microtime().

if else if

```if     (\$i===0) \$n += 0;
elseif (\$i===1) \$n -= 1;
elseif (\$i===2) \$n -= 2;
elseif (\$i===3) \$n += 3;
elseif (\$i===4) \$n += 4;
elseif (\$i===5) \$n -= 5;
elseif (\$i===6) \$n -= 6;
elseif (\$i===7) \$n += 7;
elseif (\$i===8) \$n += 0;
elseif (\$i===9) \$n -= 1;
elseif (\$i===10) \$n -= 2;
elseif (\$i===11) \$n += 3;
elseif (\$i===12) \$n += 4;
elseif (\$i===13) \$n -= 5;
elseif (\$i===14) \$n -= 6;
elseif (\$i===15) \$n += 7;```

case switches

```switch (\$i) {
case 0:
\$n += 0;
break;
case 1:
\$n -= 1;
break;
case 2:
\$n -= 2;
break;
case 3:
\$n += 3;
break;
case 4:
\$n += 4;
break;
case 5:
\$n -= 5;
break;
case 6:
\$n -= 6;
break;
case 7:
\$n += 7;
break;
case 8:
\$n += 0;
break;
case 9:
\$n -= 1;
break;
case 10:
\$n -= 2;
break;
case 11:
\$n += 3;
break;
case 12:
\$n += 4;
break;
case 13:
\$n -= 5;
break;
case 14:
\$n -= 6;
break;
case 15:
\$n += 7;
break;```

nested if

```if (\$i<8) {
if (\$i < 4) {
if (\$i < 2) {
if (\$i===0) \$n += 0;
else \$n -= 1;
} else {
if (\$i===2) \$n -= 2;
else \$n += 3;
}
} else {
if (\$i < 6) {
if (\$i===4) \$n += 4;
else \$n -= 5;
} else {
if (\$i===6) \$n -= 6;
else \$n += 7;
}
}
} else {
if (\$i < 12) {
if (\$i < 10) {
if (\$i===8) \$n += 0;
else \$n -= 1;
} else {
if (\$i===10) \$n -= 2;
else \$n += 3;
}
} else {
if (\$i < 14) {
if (\$i===12) \$n += 4;
else \$n -= 5;
} else {
if (\$i===14) \$n -= 6;
else \$n += 7;
}
}
}```

## Results

The results were stated as:

• If else if’s: 0.455 seconds.
• Case switch: 0.331 seconds.
• Nested if statements: 0.256 seconds.

Nested if statements were the fastest, followed by case switches although the difference is hardly noticeable nor massive between each corresponding type.

The use of each type can be seen as personal preference however the more nested a statement is the harder it is to read. For me, if else is traditional with the switch case being longer in form.