(click anywhere to close)

[PHP] Control Flow II

category: Website | course: PHP | difficulty:

Last chapters introduced lots of useful blocks we can use to control the flow of a system, and before we go on to more exciting stuff, I want to provide some alternative syntaxes that might come in handy someday. I’d also like to introduce a very useful feature: inserting the contents of other PHP files into the current file.

The switch Statement

Suppose that we have a system that checks for multiple states in a sign up process. If a user clicks sign up, we start at state 0, where he can choose a name. When finished, we go to state 1, where the user can input his email. This goes on until we’ve reached state 20.

Now, we could use an if–elseif–else block to check for all those states, but I wouldn’t like to be in your position if you had to write that out. Instead, for checking the same expression against different values, we can use the more readable switch statement. The syntax is:

switch(expression) { case value1: code case valuen: code }

This checks the expression against the different cases, and executes the code underneath a case if it matches. So, in normal language: in case the expression is this value, execute the code underneath it.

//A system for leveling up users if they do something awesome on your website
$level = 2;
$status = "";

if($level == 0) {
	$status = "Beginner";
} else if($level == 1) {
	$status = "Professional";
} else {
	$status = "Wizard";

switch($level) {
	case 0:
		$status = "Beginner";
	case 1:
		$status = "Professional";
	case 2:
		$status = "Wizard";

The switch statement, however, by default executes everything underneath a certain case – which is called falling through cases. This can be useful if you want to execute multiple blocks of code on certain occasions, but more often than not you don’t want it. To break out of the statement we – not surprisingly – use the break keyword again.

$result = 0;

switch($value) {
	case 0:
	case 1:
		$result += 5;
	case 2:
		$result -= 5;

//If $value is 0, $result will be 1
//If $value is 1, $result will be 0
//If $value is 2, $result will be -5

Lastly, just as the else statement, we would like to have a default block of code that should be executed if all the other cases are not matched. For this, we use the default keyword.

$search_query = "Panda";

switch(strtolower($search_query)) {
	case "tiger":
		//Display the page about tigers
	case "panda":
		//Display the page about pandas
		//Display the page with an overivew of all animal species

The Alternative Syntax

For most of its control structures, PHP offers an alternative syntax that you may or may not like better. This alternative syntax only replaces the opening and closing braces ( { } ). It can be applied to the if, else if, else, for, foreach, and switch statements.

The opening brace is replaced with a colon ( : ). The closing brace is replaced by a word that depends on the control structure: endif, endfor, endforeach, and endwhile.

//Regular syntax
if($post_category == "") {
	echo "This post was unassigned";
} else {
	echo "Category: $post_category";

//Alternative syntax
if($post_category == ""):
	echo "This post was unassigned";
	echo "Category: $post_category";

The rest of the syntax is the same, and their function is identical. So, it’s mostly a matter of preference.

Do not, however, mix braces and this alternative syntax in one code block.

The goto Keyword

Ye be warned! The goto keyword is powerful, but evil. With it, you can jump to any other part of the program any time you want. This can save your life, but it also makes code unreadable and can easily lead to indecipherable errors. If you’re in a situation you feel you should use this keyword, you should first check with yourself: is there really no way to restructure this program to solve all my problems?

Let’s see how it works. To be able to specify where we want to jump to, we need to label a certain position in the code. This is done with the simple colon syntax:


Note that this label is not a string, and doesn’t need quotes around it. The syntax for going to that label is then

goto some_label;
$x = 0;
my_label: $x++;
if($x < 10) {
	echo $x;
	goto my_label;
//Prints 123456789

//But please, just use loops (or functions) instead.

Including Code

As promised, PHP allows you to easily import the contents from another PHP file. For example, most websites import the same PHP file containing the header/navigation at the top of every page. This way, if they ever were to change the navigation, they can just edit that single PHP file and everything will be fine.

Because this functionality so important, it’s a language construct (just as echo), and uses functions that don’t need parentheses around the parameter. In fact, PHP is faster without the parentheses. There are four functions for including code, all with slight differences:



include "pathtofile"

Includes the file. If it can’t find the file at the path specified, it will search the current file’s directory. If that fails, it emits a warning.

require "pathtofile"

Same as include, but if it can’t find the file, it throws an errors and halts further execution.

include_once "pathtofile"

Same as include, but checks if the file has already been included somewhere. If that’s the case, it doesn’t do anything.

require_once "pathtofile"

Same as require, but checks if the file has already been included somewhere. If that’s the case, it doesn’t do anything.

So, if your program strictly depends on a file, use require. Otherwise, use include.

/** content of header.php **/
	echo "<html><head>";
	echo "<title>Awesomewebsite - Your credible source for information</title>";
	echo "</head><body>";

/** content of footer.php **/
	echo "<footer>Copyright Awesomeness Inc.</footer>";
	echo "</body></html>";

/** Every other page on the website **/
	include "header.php";
	lots of HTML code
	include "footer.php";
Do you like my tutorials?
To keep this site running, donate some motivational food!
Chocolate Milk