Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.2If statements in PHP

Part 4.2If statements in PHP

If Statements

An if statement checks a Boolean BooleanThis is either true or false. It is oftenrepresented by a 0 or a 1 (binary) in programming languages. statement to see if what is being asked is true. If it is true, the program executes one path of code in one way and if not true (false) then it does not execute it. If statements are fundamental to any programming language.

In PHP, an If Statement can be written as shown in the following code sample:

PHP
<?php
    //Simple if statement to output Yes if true.
    $test1 = 3;
    $test2 = 5;
    if ($test1 < $test2) {
        echo 'Yes';
    }
?>
        
Yes

Obviously the above If Statement will output Yes as $test1 is less than $test2.

Else

Having an else in an if statement allows a separate path to be executed when the condition is not satisified. For the previous example, the program could output no when the value of $test1 is greater than (or equal to) $test2.

PHP
<?php
    //Simple if statement to output Yes if true.
    $test1 = 5;
    $test2 = 5;
	if ($test1 > $test2) {
		echo 'Yes';
	} else {
		echo 'No';
	}
?>
        
No

Else if

The next example has multiple conditions. This example will take a look at how to use elseif in the if statement. This creates another opportunity of a code path by determining if the result is one not specified by the if statement.

PHP
<?php
    /*
    *Simple if statement to output Greater than if x is greater than y,
    *Or Equal to if x and y are equal
    *Or Less than otherwise
    */
    $test1 = 5;
    $test2 = 5;
    if ($test1 > $test2) {
        echo 'Greater than';
    } elseif ($test1 == $test2) {
        echo 'Equal to';
    } else {
        echo 'Less than';
    }
?>
        
Equal to

Thus, this example gives more flexibility than a standard if statement inside the else code path of an If Statement (a nested if statement). There can be as many elseif conditions within an if statement as necessary.

Feedback 👍
Comments are sent via email to me.