Sun. Oct 6th, 2024

PHP – If/Else

Using these conditional statements can add a new layers of “cool” to your website. Here’s the basic form of an if/else statement in PHP.

PHP Code:

$number_three = 3;

if ( $number_three == 3 ) {
	echo "The if statement evaluated to true";
} else {
	echo "The if statement evaluated to false";
}

Display:

The if statement evaluated to true

This is a lot to digest in one sitting, so let us step through the code, line by line.

  • We first made a PHP variable called $number_three and set it equal to 3.
  • In this example we compared a variable to an integer value. To do such a comparison we use “==“, which in English means “Is Equal To”.
  • $number_three is indeed Equal To 3 and so this statement will evaluate to true.
  • All code that is contained between the opening curly brace “{” that follows the if statement and the closing curly brace “}” will be executed when the if statement is true.
  • The code contained within the else segment will not used.

Execute Else Code with False

On the other hand, if the if statement was false, then the code contained in the else segment would have been executed. Note that the code within the if and else cannot both be executed, as the if statement cannot evaluate to both true and false at one time! Here is what would happen if we changed to $number_three to anything besides the number 3.

PHP Code:

$number_three = 421;

if ( $number_three == 3 ) {
	echo "The if statement evaluated to true";
} else {
	echo "The if statement evaluated to false";
}

Display:

The if statement evaluated to false

The variable was set to 421, which is not equal to 3 and the if statement was false. As you can see, the code segment contained within the else was used in this case.

6,698 total views, 1 views today