PHP Conditional Statement
PHP Conditional Statement also known as PHP Ternary operator is used to check conditions of a logical syntax.
The Typical Ternary conditions Statement, is to check the syntax condition. If the Condition is “true” the Statement will output a specific value, else if not , it will output another value.
PHP IF Conditional Statement
In this Example I will use an If Else Conditional Statement.I have assigned $a , and $b to have the Same value equal to 5.
In the mean time i have set my conditional Statement as If variable $a does not equal to $b is True.Assign’ Not Equal ‘ String into Variable $c.
In this Context Condition ($a != $b) stand for “$a not equal $b “is ” False “so it Skip the If statement, and print out “echo $c;” directly.
Result: Output will be ” Equal”.
Well if i change $a= 6; and $b=5; remains as 5 . When the conditional statement run through a check. Condition ($a != $b) stand for “$a not equal $b “will be ” True “.
The String ” Not Equal ” will be assign into Variable $c.
Result: Output will be ” Not Equal”.
. <?php $a = 5; $b = 5; $c = 'Equal'; if( $a!=$b) { $c= 'Not equal'; } echo $c; ?>
PHP IF Else Conditional Statement
Now i expand the IF Conditional Statement into a IF else Conditional Statement.If ” this Statement ” is not true , else” Do something else ”
I moved the ‘ Equal ‘ Assignment into the else function. If the variable $a and $b are ‘ Not equal’ move the ‘ Not Equal’ string into Variable $c . Else if the variable $a and $b are ‘Equal’ , move the ‘Equal’ String into variable $c.
<?php $a = 5; $b = 5; if( $a!=$b) { $c= 'Not equal'; } else { $c = 'Equal'; } echo $c; ?>
PHP IF ‘ Else if’ , Else Conditional Statement
Now i expand the logic to If,elseif and else.
I have change the first condition to” if( $a==$b)” Stands for if the value $a is the same as $b.
and i add “elseif($a<=$b)” Stands for elseif $a is less than or equal to $b
Results: The First condition does not met as $a=5 and $b =6.when the program scan towards the Second Condition, “elseif($a<=$b)” , the Condition was satisfied , and then it will assign the value ‘b is greater than a’ into variable $c. As the Condition is met, it will skip the default “else ” condition and directly print out the $c value. Final Print out $c value is’b is greater than a’.
<?php $a = 5; $b = 6; if( $a==$b) { $c= 'Not equal'; } elseif($a<=$b) { $c= 'b is greater than a'; } else { $c = 'Equal'; } echo $c; ?>
Check out PHP operator