Please wait

Flow Control

Flow control in PHP refers to how a script, or a program, can make decisions based on conditions and execute specific parts of the code depending on the outcome of those conditions. In other words, flow control determines how a program will "flow" from one set of instructions to the next.

It is important because it allows a PHP script to make decisions and adapt its behavior based on changing conditions. For example, you can use flow control to test if a certain condition is true, and if it is, execute one set of instructions, while if it is not, execute a different set of instructions. This enables a program to respond differently to various inputs, or to handle different scenarios, making the code more flexible, reusable, and scalable.

For example, let's say we wanted to render a link for logging in or out. Which link should we render? That answer will be based on if the user is logged into our website.

Flow Control
Flow Control

It's not uncommon to face these types of situations. This is where flow control can help you make decisions in your application.

Some of the most commonly used flow control statements in PHP are if-else statements, switch statements, while and do-while loops, and for loops. By combining these statements, you can create more complex programs that can respond to different conditions and make decisions based on those conditions.

We'll be looking at each of these features in more detail. Let's start with if-else statements.

if statement

An "if" statement in PHP is a type of flow control statement that allows the program to make decisions based on conditions. It tests if a certain condition is true, and if it is, executes a block of code. The basic syntax of an if statement in PHP is as follows:

The "condition" in the parentheses can be any expression that returns a boolean value (true or false). If the condition is true, the code inside the curly brackets will be executed. Curly brackets are commonly used for grouping statements. It lets PHP know where a code block begins and ends. You can write as many statements as you'd like within these curly brackets. In addition, it's not required to add a ; character after the closing } character. PHP automatically interprets this character as ending the block of code.

If the condition is false, the code inside the brackets will be skipped, and the program will move on to the next instruction.

if (condition) {
  // code to be executed if the condition is true
}
 
 
 

If statement example

In this example, the condition $x > 4 evaluates to true, so the message "x is greater than 4" will be displayed.

$x = 5;
 
if ($x > 4) {
  echo "x is greater than 4";
}

Optional syntax

Curly brackets are optional when you only have one line of code. Here's the same example without the curly brackets.

However, it's always recommended to use curly brackets for readability.

$x = 5;
 
if ($x > 4)
  echo "x is greater than 4";

else statement

An "else" statement in PHP is used in combination with an "if" statement to provide an alternate set of instructions to be executed if the condition tested by the "if" statement is false. The basic syntax of an if-else statement in PHP is as follows:

In this example, the condition in the parentheses is first tested by the "if" statement. If the condition is true, the code inside the first set of curly brackets will be executed. If the condition is false, the code inside the "else" statement will be executed instead.

if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
 
 
 

else statement example

In this example, the condition $x > 6 is false, so the message "x is not greater than 6" will be displayed.

$x = 5;
 
if ($x > 6) {
  echo "x is greater than 6";
} else {
  echo "x is not greater than 6";
}

elseif statement

An "elseif" statement in PHP is used in combination with an "if" statement to provide additional conditions that can be tested. It allows you to test multiple conditions in a single "if" statement and execute different code blocks based on the outcome of each test. The basic syntax of an if-elseif-else statement in PHP is as follows:

In this example, the conditions in the parentheses are tested one by one, starting with condition1. If a condition is true, the code block corresponding to that condition will be executed, and the rest of the conditions will be skipped. If all conditions are false, the code block inside the "else" statement will be executed.

if (condition1) {
   // code to be executed if condition1 is true
} elseif (condition2) {
   // code to be executed if condition1 is false and condition2 is true
} elseif (condition3) {
   // code to be executed if condition1 and condition2 are false and condition3 is true
} else {
   // code to be executed if all conditions are false
}

elseif statement example

In this example, the condition $x > 6 is false, but the condition $x > 4 is true, so the message "x is greater than 4 but not greater than 6" will be displayed.

The else block never executes either since a previous condition passes.

$x = 5;
 
if ($x > 6) {
  echo "x is greater than 6";
} elseif ($x > 4) {
  echo "x is greater than 4 but not greater than 6";
} else {
  echo "x is not greater than 4";
}

Alternative syntax

In PHP, there is an alternative syntax for the if, elseif, and else statements that use a colon (:) instead of curly brackets ({}) to define the code blocks. This alternative syntax is sometimes referred to as the shorthand syntax. The basic syntax of an if-elseif-else statement using the shorthand syntax is as follows:

if (condition1):
   // code to be executed if condition1 is true
elseif (condition2):
   // code to be executed if condition1 is false and condition2 is true
elseif (condition3):
   // code to be executed if condition1 and condition2 are false and condition3 is true
else:
   // code to be executed if all conditions are false
endif;

The chain of conditional statements must always end with the endif keyword. This alternative syntax is useful when writing short or simple code blocks, as it saves you from having to use curly brackets and can make the code more readable and easier to write.

Additionally, it can be useful in situations where you want to mix HTML and PHP code, as it allows you to write PHP code in line with HTML code. For example:

<?php $x = 5; ?>
 
<?php if ($x > 6) : ?>
  <h1>x is greater than 6</h1>
<?php elseif ($x > 4): ?>
  <h1>x is greater than 4 but not greater than 6</h1>
<?php else: ?>
  <h1>x is not greater than 4</h1>
<?php endif; ?>

In general, the choice of whether to use curly brackets or shorthand syntax is a matter of personal preference, and either can be used depending on the context and the needs of the specific situation. As a general rule of thumb, if you're writing pure PHP, stick with curly brackets. However, if you need to write HTML, the alternative syntax is used for readability.

Common Mistakes

Oftentimes, beginners may find themselves using the wrong operator when creating conditions within a conditional statement. They may use the assignment operator (=) when they meant to use the equal to operator (==).

For example, take the following:

$x = 5;
 
if ($x = 6) {
  echo '$x is equal to 5';
}

In this example, we're not comparing the variable $x with the number 6. Instead, we're assigning a value to the variable, which will cause the condition to evaluate to true. This mistake does not throw an error in PHP. It's considered to be completely valid code.

You can avoid scenarios like this by always placing the variable at the end of the condition. This is known as a yoda conditions.

$x = 5;
 
if (6 = $x) {
  echo '$x is equal to 5';
}

This time, if you were to make the same mistake by using a single = character, PHP will throw an error. In the first example, PHP doesn't throw an error, which can make it hard to debug your application. However, with the second example, the error will help you debug your program.

This technique is optional, but it can be helpful to beginners to avoid this common mistake.

Ternary Operators

The ternary operator is a shorthand way to write an if-else statement. It's called a "ternary" operator because it takes three operands: a condition, a result for when the condition is true, and a result for when the condition is false.

The basic structure of the ternary operator in PHP is as follows:

condition ? expression if true : expression if false;

Let me give you a simple example. Imagine we have a variable called $age, and we want to check if this person is an adult (18 years or older). Using an if-else statement, we might write something like this:

if ($age >= 18) {
  $status = "Adult";
} else {
  $status = "Minor";
}

Now, we can achieve the exact same result using the ternary operator:

$status = $age >= 18 ? "Adult" : "Minor";

As you can see, the ternary operator makes your code more compact. It's particularly useful when you're assigning a variable based on a condition or when you're returning a value from a function.

Multiple Ternary operators

You can nest ternary operators within each other to handle more complex conditional logic. This is often referred to as "chaining" the ternary operator. However, it's important to note that while this can make your code more compact, it can also make your code more difficult to read and understand, so it should be done with care.

Here's an example where we're evaluating a person's age and returning different strings based on the age:

$age = 20;
$description = $age < 13 ?
  "Child" :
  ($age < 18 ? "Teen" : "Adult");
echo $description; // Outputs "Adult"

In this example, if $age is less than 13, "Child" is returned. If $age is 13 or more, then we go to the next condition, which checks if $age is less than 18. If it is, "Teen" is returned. Finally, if $age is 18 or more, "Adult" is returned.

Essentially, the code breaks down like this:

  • If $age is less than 13, the person is a "Child".
  • If $age is 13 to 17, the person is a "Teen".
  • If $age is 18 or more, the person is an "Adult".

You'll notice that I'm writing the ternary operators on multiple lines of code. This is optional but can be helpful for readability. In addition, the second ternary operator is wrapped with parentheses (()), which is required by PHP for nested ternary operators. Only the inner ternary operators need to be wrapped with parentheses.

While this is a simple example, you can see how nested ternary operators could become hard to read if you have many conditions. In such cases, it might be better to use traditional if-else statements for the sake of code readability.

Exercises

Exercise #1

Will the message be displayed on the page?

if ("0") {
  echo 'Hello';
}

Exercise #2

Create a variable for storing the user's bank account type. A message should be displayed to inform the user of their account type.

  • Users with checking accounts should be greeted with the message "Welcome to your checking account."
  • Users with savings accounts should be greeted with the message "Welcome to your savings account."
  • If the user doesn't have either account, they should be told their account type is not supported.

Exercise #3

Rewrite this if using the conditional operator '?':

$result;
 
if ($a + $b < 4) {
  $result = 'Below';
} else {
  $result = 'Over';
}

Exercise #4

Rewrite if..else using multiple ternary operators '?'.

For readability, it's recommended to split the code into multiple lines.

$message;
 
if ($login === 'Employee') {
  $message = 'Hello';
} else if ($login === 'Director') {
  $message = 'Greetings';
} else if ($login === '') {
  $message = 'No login';
} else {
  $message = '';
}

Key takeaways

  • Flow control in PHP refers to the way that a script, or a program, can make decisions based on conditions and execute specific parts of the code depending on the outcome of those conditions.
  • The if keyword allows us to execute a block of code if a condition is true.
  • The elseif keyword will execute a block of code if a condition is true and the condition before it failed.
  • else keyword will execute a block of code if all other conditions before it failed.
  • A ternary operator is a shorthand syntax for writing a conditional statement. The format is the following: condition ? value1 : value2
  • You should avoid using nested ternary operators as they can be difficult to read. Traditional conditional statements are preferred for a complex chain of conditions.

Comments

Please read this before commenting