Added fall-through documentation & return notation (#19428)

* Added fall-through documentation & return notation

Fall-through is an important feature of switch statements. In addition, best practices with break-usage have been included.

* fix: added closing switch curly braces

* fix: corrected link syntax
This commit is contained in:
NirvashPrime
2018-10-15 23:57:51 -04:00
committed by Randell Dawson
parent fa6a0fc8d5
commit 0cd8496ad0

View File

@ -19,7 +19,8 @@ In PHP, the `Switch` statement is very similar to the Javascript `Switch` statem
echo "i is camp";
break;
default:
echo "i is freecodecamp";
echo "i is freecodecamp";
break;
}
```
@ -27,5 +28,61 @@ In PHP, the `Switch` statement is very similar to the Javascript `Switch` statem
### Break
The `break;` statement exits the switch and goes on to run the rest of the application's code. If you do not use the `break;` statement you may end up running mulitple cases and statements, sometimes this may be desired in which case you should not include the `break;` statement.
An example of this behavior can be seen below:
```
<?php
$j = 0
switch ($i) {
case '2':
$j++;
case '1':
$j++;
break;
default:
break;
}
```
If $i = 1, the value of $j would be:
```
1
```
If $i = 2, the value of $j would be:
```
2
```
While break can be omitted without causing fall-through in some instances (see below), it is generally best practice to include it for legibility and safety (see below):
```
<?php
switch ($i) {
case '1':
return 1;
case '2':
return 2;
default:
break;
}
```
```
<?php
switch ($i) {
case '1':
return 1;
break;
case '2':
return 2;
break;
default:
break;
}
```
#### More Information:
* <a href="https://secure.php.net/manual/en/control-structures.switch.php" rel="nofollow">php.net docs Switch</a>
* [php.net docs Switch](https://secure.php.net/manual/en/control-structures.switch.php")