PHP - Control Structures - Control Structures

Control Structures

The heart of PHP is the control structures. Variables and arrays are lonely without them as they facilitate comparisons, loops, and large hands telling you to go that way and do it this way. Okay, I made that last part up. Here we go..!

If, ElseIf, Else
if (expr) {
// If expr is TRUE, do this, then exit the IF loop
}elseif (expr2) {
// If expr is FALSE, and expr2 is TRUE, do this, then exit the loop
// If all expr's are FALSE, do this, then exit

There can be only one instance of else in an if statement, but multiple elseif expressions are allowed prior to the else statement.

$x = 1;
if ($x < 1){
echo '$x is less than 1';
}elseif ($x == 1){ // Note the double equals, for comparison
echo '$x is equal to 1';
echo '$x is neither equal to 1 or less than 1';
$x is equal to 1

Switch Statement

A simpler, more organized usage than multiple if/elseIf Combinations Break stops a loop and exits regardless of if the statement evaluates as true

switch (expr) {
case value:
// Do this if value matches
case value2:
// Do this if value2 matches
default: // [optional]
// Do this if no other cases match. Does not have to be at the end