While writing code, when you want to perform different actions depending on conditions you will use a conditional statement in your code
Example:
1 2 3 |
if(condition is true) { //do something } |
If the condition is true the block will execute otherwise whole block will be ignored. If you have some alternative condition then we use else
1 2 3 4 5 |
if(condition is true) { //do something }else{ //do something different } |
You can chain condition also
1 2 3 4 5 6 7 |
if(condition is true) { //do something } elseif{ //do another task } else { //Do something different } |
If the first condition is true first is executed and if second is true second is executed but if both are true only first is executed.
Operator | Meaning | Operator | Meaning |
---|---|---|---|
=== | Identical | !== | Not Identical |
< | Less than | > | Greater than |
<= | Less than or equal | >= | Greater than or equal to |
Note:
- Always use a double equal sign for if statement using single equal will always evaluate to true as it assigns a value instead of comparing it.
- Difference between equal and identical refers to data type. For example
1 2 3 4 5 6 7 8 9 10 |
$var = 47 ; $var2 = '47'; if($var == $var2){ echo "Both are equal"; } if($var === $var2){ echo "both are identical"; } |
Here both are equal, not identical.
Example of if/else if/else
1 2 3 4 5 6 7 8 9 |
$name = 'Kritika' ; $age = 27; if($name == 'kritika' && $age==27){ echo "my name is correct"; }elseif($name == 'devesh' || $age==27){ echo "name is not correct"; }else{ echo "else part"; } |
Other syntax for if else
We can avoid braces and use the following syntax for if else condition also
1 2 3 4 5 6 7 8 9 |
$name = 'Kritika' ; $age = 27; if($name == 'kritika' && $age==27): echo "my name is correct"; elseif($name == 'devesh' || $age==27): echo "name is not correct"; else: echo "else part"; endif; |
Note: when using braces elseif can be broken into two words however here elseif is written as one word only.