PHP if-else Statements 🎯

beginner
19 min

PHP if-else Statements 🎯

Welcome to our comprehensive guide on PHP if-else Statements! In this lesson, we'll learn about making decisions in PHP using if-else statements. By the end, you'll be able to write confidently and control the flow of your code. πŸ“

What are if-else Statements?

If-else statements in PHP are used to make decisions in your code. They allow you to execute different blocks of code based on conditions you define. Let's start by understanding the basic if statement.

php
if (condition) { // code to execute if condition is true }

In the above example, replace condition with a boolean expression, such as:

php
if (5 > 3) { echo "5 is greater than 3"; }

When you run the code, it will output: 5 is greater than 3. This is because the condition 5 > 3 is true, so the code inside the if block is executed.

Understanding else Statements πŸ’‘

Now let's add an else statement to handle cases when the condition is false.

php
if (condition) { // code to execute if condition is true } else { // code to execute if condition is false }

For example:

php
if (5 < 3) { echo "5 is less than 3"; } else { echo "5 is not less than 3"; }

The output will be: 5 is not less than 3, because the condition 5 < 3 is false, so the code inside the else block is executed.

if-else Ladders 🎲

When you have multiple conditions to check, you can use an if-else ladder:

php
if (condition1) { // code to execute if condition1 is true } else if (condition2) { // code to execute if condition1 is false and condition2 is true } else if (condition3) { // code to execute if condition1 and condition2 are false and condition3 is true } else { // code to execute if all conditions are false }

Here's an example:

php
$number = 10; if ($number > 15) { echo "The number is greater than 15"; } else if ($number > 10) { echo "The number is between 10 and 15"; } else if ($number > 5) { echo "The number is between 5 and 10"; } else { echo "The number is less than 5"; }

The output will be: The number is between 10 and 15.

Quiz πŸ“

Quick Quiz
Question 1 of 1

Which PHP statement allows you to make decisions in your code?

Quick Quiz
Question 1 of 1

Which of the following blocks of code handles the case when the condition is false?

Quick Quiz
Question 1 of 1

What does an if-else ladder do?