OneBite.Dev - Coding blog in a bite size

If Else Conditional Statement In PHP

Code snippet for how to If Else Conditional Statement In PHP with sample and detail explanation

PHP as a server-side scripting language offers several control structures to manage the flow of the program. One of the most common structures is the ‘if-else’ conditional statement, which helps in decision making based on specific conditions.

Code snippet: If Else Conditional Statement in PHP

Let’s look at a basic example:

$age = 20;

if ($age < 18) {
  echo 'You are a minor';
} else {
  echo 'You are a grownup';
}

As seen above, we are using the if-else conditional statement to print a specific message based on a person’s age.

Code Explanation: If Else Conditional Statement in PHP

The if-else statement allows PHP to make decisions based on conditions. The script inside the ‘if’ block will execute when the condition is ‘true’. If it is ‘false’, then the script inside the ‘else’ block will execute.

In the provided PHP snippet:

  1. We declare a variable $age and assign it the value 20.

  2. The if statement checks the condition $age < 18. If this condition is true, it will execute the code block inside the if statement.

  3. In our case, the age is 20 which is not less than 18, so the condition is false.

  4. Since the if condition is not met, we move to the else statement. There’s no condition associated with the else block, it simply runs when the if condition fails.

  5. So, the script inside the else block executes and it prints the message “You are a grownup”.

That’s how an if-else conditional statement operates in PHP. It is used to validate conditions and execute code accordingly. This form of control structure enhances the functionality of PHP, allowing it to make decisions and perform different actions based on varying circumstances.

php