(click anywhere to close)
OPEN MENU

[PHP] Control Flow

category: Website | course: PHP | difficulty:

Now that we’ve seen how to create conditionals, we can look at how to actually use them. The name of this chapter – Control Flow – is just a fancy name for controlling which parts of the code the program executes, and which it doesn’t. You can use the result of conditionals to control the flow of a program; does it go into this direction, or that direction?

To do so, we have if statements (and its related brothers and sisters). They are quite intuitive actually; if a certain condition is true, do that. Because you’ll be using some kinds of if statements a lot, PHP also provides a few special conditional operators again to make our lives easier.

The if Statement

To execute a certain block of code only if a certain condition is true, we use

if(condition) { lots of statements }
$logged_in = ($password === "1234" && $username === "Ginty");

//If the username and password entered are correct...
if($logged_in) {
	//...welcome the logged in user
	echo "Welcome, $username!";
}

The else Statement

Once upon a time, there was a game that changed its settings based on what time it was. If it was night, it would display a dark background, if it was day, it would display a light background. Undoubtedly, this game used an else statement.

An else statement is executed if the condition within the preceding if statement returns false. In normal language you would say: if this condition is true, do this, else do that. The syntax is

else { lots of statements }
$hours = 20;

//If it's morning or afternoon...
if($hours <= 18) {
	echo "Good day!";
//Else if it's night ($hours > 18)
} else {
	echo "Good night!";
}

The else if Statement

Now, suppose that game wanted to be more dynamic and display three different backgrounds. Night would mean a black background, daylight a bright background, and morning a neutral background. This would be the perfect situation for an else if statement!

The else if statement is executed when the previous condition is false, and checks for a new condition. In normal language: if this condition is true, do this, else if this other condition is true, do that. The syntax is

else if(condition) { lots of statements }

You can put as many of these after each other as you need. The first must, however, always follow an if statement.

$hours = 20;

if($hours < 12) {
	echo "Good morning!";
} else if($hours <= 18){
	echo "Good day!";
} else {
	echo "Good night!";
}

The else statement, if you decide to include it, must always be put at the end of such an if–elseif construction. In any case, it only executes if all the other conditions have returned false.

It’s highly recommended to always use else as the last statement in the construction, and not else if. That’s because the latter requires another condition, which requires more work from you to type, and if anything changes within the program, you have to change that condition as well.

The Ternary Operator

By far the most common conditional structure you’ll use is: if this condition is true, set a variable to that value, else set it to another value. That’s why the ternary operator was invented to reduce the amount of work! The syntax is:

$variable = condition ? value if true : value if false;
// A simple piece of code to make a player in a game
// face in the direction he's running
$player_velocity = -20;

//LONG syntax
if($player_velocity > 0) {
	$player_direction = 1;
} else {
	$player_direction = -1;
}

//SHORT syntax
$player_direction = ($player_velocity > 0) ? 1 : -1;

The Spaceship Operator

Another common conditional structure, is where you want to check whether two values are the same, or if one is less/greater than the other. You could do this with an if-elseif-else statement, but the spaceship operator (dumdumdumduuuum) makes this much easier.

It compares the two operands, and

  • Returns 0 if both operands are equal
  • Returns 1 if the left operand is greater
  • Returns -1 if the right operand is greater.

The syntax is:

x <=> y
$points_player_1 = 160;
$points_player_2 = 240;

$result = $points_player_1 <=> $points_player_2;

if($result === 0) {
	echo "It's a tie";
} else if($result === 1) {
	echo "Player 1 won!";
} else {
	echo "Player 2 won!";
}

Null Coalescing

The last common conditional structure, is one where you want to check whether some variable is null before you start doing anything with it. Because, if you don’t, you’ll likely run into lots of errors because the variable isn’t properly set. To easily set a default value for a variable if it happens to be null, use the null coalescing operator. The syntax is

x ?? y

Because it’s an operator, you can chain it as many times as you want. In that case, it will return the first value that is not null.

//Say a user requested a blog post.

//If, for some reason, the post can't be found and the request returns null..
//display the newest post to satisfy the user - if that returns null as well...
//display an error page saying that the post could not be found
$post = $requested ?? $newest ?? $error_404_page;

Integration with HTML

Here I just want to point out the very important property of PHP we also saw at the beginning – it integrates seamlessly with HTML. So, we don’t have to restrict our control structures to PHP statements only. We can place an if statement, then break out of PHP mode and write some regular HTML/CSS/JavaScript, and then get into PHP mode again to close the if statement. This way, we let PHP decide whether whole chunks of HTML are displayed or not, based on certain conditions.

<?php
	if($current_url == "search.php") {
?>

	<p>Give us a moment, and we will search our database for what you were looking for!</p>

<?php
	} else {
?>

	<p>Welcome to <span>awesomewebsite.com</span>! I hope you enjoy your stay.</p>

<?php
	}
?>
CONTINUE WITH THIS COURSE
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)