PHP Decision Making Statements

PHP Decision Making Statements

We saw in the previous lesson, how to work with PHP loops, while, do..while, for and for…each. Now, we learn PHP statements with examples and illustrations. With PHP decision making statements, such as if…else, if…else…elseif, switch, etc, you can easily take decision based on different conditions.

Let’s discuss the decision making statements,

if statement

The if decision making statement executes the code, if the condition is true.

Here’s the syntax,

Example

Here, the code executes if the condition $a > 5 is true. The value of a is greater than 5, so the if statement executes and prints, We’re learning PHP,

Here’s the output,

PHP decision making statements - if statement

if…else statement

The if…else decision making statement executes some code if the condition is true and another code if the condition is false. The false condition comes under else.

Here’s the syntax,

Example

The value of $a = 10, so the first statement won’t execute, since its condition is $a < 5.
However, the second statement else execute and prints We’re learning Python as shown below,

Here’s the output,

PHP if else decision making statement

if…elseif…else Statement

The if…elseif…else statement execute code for different conditions. If more than 2 conditions are true, you can use else for the false condition.

Here’s the syntax,

Example

Here, $a = 5, so the else condition gets executed.

Here’s the output,

PHP elseif decision making statement

PHP Switch Statement

If you want to avoid using long code for if…elseif…else, then use switch statement. Under switch, you can add many blocks of code and select one at a time.

Here’s the syntax,

Example

Here, the Java topic gets printed as output.

Here’s the output,

PHP switch decision making statement

Here, we saw how to work with PHP Decision making statements, if, if..else, if…else…elseif, switch, etc.

PHP Loops
PHP Arrays
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create free tutorials for all.

No Comments

Post A Comment