Articles

Free online Tutorial PHP

PHP logic Lesson 6 Tutorial Tutorials PHP

6. Comparison Logic using condition operators

6. Comparison Logic using condition operators

Using operators in logical statements is a core skill for programming. If statements really do ask the question if something is this way, this will happen. A question meet by a response. Conditional logic statements can be used to create predetermined output in a scenario. The if is syntax used bracketing the logic and then curly brackets for the result if the case is met.

PHP Code example

if($a==1)
{
echo 'The variable did equal 1';
}

The code above would run and ask the question is the value of $a equal to 1. If it is True that $a equals 1 then it would output the text 'The variable did equal 1'

If the result of the logic comes back negative or false the bracketed text would not be displayed. It would not run any of the code between the brackets within the if statement. If you want to provide a specific output if its false and does not meet the criteria you can do it with an else statement. Else builds a more complex logical condition.

PHP Code example

if($a==1)
{
echo 'The variable did equal 1';
} else {
echo 'The variable did NOT equal 1';
}

The above code will output a different response depending on the value of $a. If it is not true the response will write what is contained in the else statement. When using the else statement both will not be true so only one of the bracketed codes will run.

To create even more complex if and else statements php has a syntax elseif. And yes you guessed it, it provides another possible outcome to the logic depending again on a condition.

PHP Code example

if($a==1) { echo 'The variable did equal 1'; }
elseif($a==2) {
echo 'The variable is equal to 2';
} else {
echo 'The variable did NOT equal 1 or 2';
}

the above asks the question if $a is 1 then output this message, then asks another if question, if it is 2 then output this message and finally if none of the conditions are met it will output the else message.

***
Do Not Sell My Personal Information