PHP If and PHP Else if Conditional Statement Examples

PHP conditional statements

You can use PHP If and PHP Else if conditional statements in PHP to perform different actions. These actions are based on the logic you want to perform using your code and get the result of the action.

By using the conditional statements you can perform various tests in your code and you can out certain actions based on the test either true or false.

In real life, you make certain decisions and based on this decision you perform different actions. These decisions help you to get the desired results as the output. Before taking any decision you always think of conditions, if you perform this task if you will get this type of result.

Same as in real life you can perform the conditional operation using the below type of conditional statements:

  • PHP If statement
  • PHP If…else statements
  • PHP If…elseif…else statements

PHP If statement

PHP If statement is the conditional statement you can use when you want to test one condition and execute the code when the test is true.

Syntax

Let’s take a simple example. You have a variable $x and you only want to print the string “Hello Friends” when the variable value is 9. With the use of the PHP statement, you can perform this process automatically without manually doing this.

If you stuck with the HTML codes how to do perform this task. You have the option using the PHP coding and PHP if statement.

Example 1:

Output

Hello Friends! Welcome to Tutorialdeep PHP Tutorial.

PHP If…else statements

PHP If…else statement is the conditional statement you can use when you want to execute one code if the condition is true and the other code if the condition fails.

Syntax

Let’s take a simple example. Suppose you have a variable $z and you want to print the string “I have the larger number” if the $z is greater than 10 and another string “I have the smaller number” when $z is not greater than 10. You can do so using the if…else statement in your code.

Example 2:

Output

I have the smallest number and Welcome to Tutorialdeep PHP Tutorial.

PHP If…elseif…else statements

PHP If…elseif…else statement is the conditional statement you can use when you want to perform multiple tests. You can put more than two conditions using this conditional statement.

Syntax

Now, Suppose you have a variable $z and you want to print the string “The number is 10” if the $z is equal than 10 and another string “I have the greatest number” when $z is greater than 10. If both conditions are false you want to print “The number is smaller”. You can do so using the if…elseif…else statement in your code.

Output

I have the greatest number and Welcome to Tutorialdeep PHP Tutorial.

You must also read:

Resource