Control structures in PHP

If, If/else, switch statements

An if statement evaluates if a statement is true or false and acts on that.

If statements

The syntax for if statements:
<?php
	//Here is the if statement. 1 always means true, 0 always means false. Here we see 1.
	if (1) {
	
	//This is the function that is completed if the statement is true.
		echo 'TRUE.';
		
	//The code past this point is part of an else statement, see below.
	  } else {
	  
	//This is the function that is completed if the statement is false.
		echo 'FALSE.';
	  }
?>
The code above also shows an example of an if/else statement. If/else statements function by first calling an if statement. If the statement is true, then the first part of the function is completed, else the second part of the function is completed.

Tip
By changing the 1 in the if statement above to 0, your code will display false. 1 is always true, 0 is always false. You can put almost anything in the if area, including variables, as shown below.

If/else statements

<?php
	$number = 10;
	
	if ($number==10) {
	
		echo 'This variable is equal to 10';
		
	} else if ($number==11) {
	
		echo 'Equal to eleven.';
		
	} else {
	
		echo 'Not equal.';
	}
?>	

This code above is a good use of if/else statements. As you can see, the if statement involves a variable. If the variable $number equals 10, then echo 'This variable is equal to 10'. You can use another if statement within an if statement as shown above. If $number is 11, then echo 'Equal to eleven.'. If $number does not equal either scenario, the final statement solves every other scenario. You can have unlimited 'else if' statements, but only one 'else' statement.

Switch statements

Switch statements are a more efficient way to write long if/else statements.
<?php
	$number = 1;
	
	switch ($number) {
		case 1:
			echo 'One';
		break;
		
		case 2:
			echo 'Two';
		break;
		
		case 3:
			echo 'Three';
		break;
		
		default:
			echo 'Not a number between 1-3';
		break;
	}
?>
Here is a comparison between the formatting of if/else statements and switch statements.

In switch statements, the switch essentially is the same as 'if', the 'else' is the same as 'case'. The 'break' is used to end a case.

In the above example, if the variable $number is equal to 1, then it will display 'One'. The same applies to 2 and 3, but will display 'Two' and 'Three', respectively. In switch statements, you can use 'default:' to create an option the function will use if it matches no defined case. In this example, if the number in $number is not something between 1-3, it will display 'Not a number between 1-3'.

NOTICE:
Switch statements use a colon instead of a semicolon for each case!

This page was created by Kevin Kantesaria