PHP Conditional Statements

PHP conditional statements let you write block(s) of code to perform actions based on different conditions. It lets you respond differently to inputs.

The block of code in the conditional statement will be executed if the condition is true.

The if Conditional Statement

The if conditional statement is a statement that executes a block of code if the condition is true. For example, a buyer wants to purchase an item from our store, we need to specify a condition to check if the buyer's amount is less than our item price, if this condition is true, we execute a block of code that prints out You do not have sufficient funds to purchase this item, letting the buyer know that the amount he is paying is not enough to purchase the item.

PHP if Conditional Statement Example

  Do It Yourself

The example above checks if the buyer's amount is less than our item price.

The else Conditional Statement

The else conditional statement is a statement that executes a block of code if the condition of the if statement is false. In the previous example, we wrote an if statement to check if the buyer's amount is less than the item's price, if the condition is false that block of code will be ignored. The else statement executes its own block of code if the condition of the if statement is false. Now, let us add to our previous example to execute a block of code if the condition of the if statement is not true. i.e. The else statement checks if the buyer's amount is greater than or equal to the item price, then we perform basic arithmetic to subtract the buyer's amount from the item price and print it out as change. Let us modify the value of the buyer's amount to execute the block of code in the else statement.

PHP else Conditional Statement Example

  Do It Yourself

The example above checks if the buyer's amount is greater than or equal to our item price.

The else if Conditional Statement

The else if conditional statement is a statement that executes multiple blocks of code based on multiple conditions. With the else if statement, you can write multiple conditions based on the user's input or data.

In the previous example, we utilized the power of the else statement and understood how it works. Now, what if we want to perform an action if the buyer's amount is equal to the item price, maybe instead of printing out zero as the change, let us use the else if statement to write the condition and perform an action if the condition is true.

PHP else if Conditional Statement Example

  Do It Yourself

The example above checks if the buyer's amount is equal to our item price and executes a block of code if the condition is true.

What You Should Know at The End of This Lesson

  • You should know about PHP conditional statements
  • You should know how to execute block(s) of code based on conditions.