ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

21 – PHP if/else Statement

In my previous lesson, I have tackled the if statement which is important in PHP when used properly and it executes some code if one condition is true.

 

This time, let’s tackle about the PHP if/else statement, obviously as its name suggests, it is a combination of if and else. However, The if/else statement performs some code if a condition is equal or true and another code will be executed if that condition is false.

 

Syntax

if (condition) {
    code to be performed if condition is true;
} else {
    code to be performed if condition is false;
}

 

Here’s a simple example of an if/else conditional statement that is common in every day life. This is to make you more familiar with it, picture the following:

“If you study hard, then you will get a passing grade”. So, what happens, if you don’t study hard? Well, you fail!

 

  • If you study hard then you will get a passing grade.
  • Else, if you don’t study hard, then you will fail.

 

Here’s an example of the basic form of PHP if/else statement:

 

$number_four = 4;

if ( $number_four == 4 ) {
	echo "The if statement performed to true";
} else {
	echo "The if statement performed to false";
}

Result:

The if statement performed to true.

 

 

perform else code with false

If the if statement was false, then the code within the else segment would not be performed. Always keep in mind that the code contained in the if and else cannot be both performed, because the if statement cannot assess to both true and false at once. Below is the result of what would happen if we changed to $number_four to anything apart from number 4.

 

Example:

$number_four = 3;

if ( $number_four == 4 ) {
	echo "The if statement performed to true";
} else {
	echo "The if statement performed to false";
}

Result:

The if statement performed to false

You will see that the variable was set to 3, which is not equal to 4 and the if statement was false. Notice that the code segment within the else was used in the given example above.

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!