If--Else

☰ Menu Content


Say you are studying for an exam.

If   you study hard you will pass the exam
Else   you will fail

How does this translate into something useful for PHP developers? Well consider this:

If--Else Example

Here is an "if--else" statement in PHP.

PHP Code:
$number = 4;

if( $number == 4 ) {
     echo "The if statement evaluated to true";
} else {
     echo "The if statement evaluated to false";}
Display:
The if statement evaluated to true

Let us step through the code, line by line.

  • First a PHP variable called "$number" was set to "4"
  • Next we compare to see if "$number" was equal to "4". To do such a comparison we use "==".
  • As "$number" is indeed Equal To "4", condition evaluated is true.
  • Therefore, "The if statement evaluated to true" is echoed.
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.

Here is what would happen if we changed to "$number" to anything but "4".

PHP Code:
$number = 421;

if ( $number == 4 ) {
     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 "4" and the if statement was false.

The code segment contained within the else was used in this case.

Note
For more detail please see Php Manual at http://www.php.net

Php Tutorial Content (menu)