The ‘If’ comes wherever options come. Where there is more than one option for anything for any matter we have to decide. In programing we use one of the method to handle this is by using If and if else statements, also known as decision making statements – to take decisions based on different situations.
Quick Reach
Three types of decision making statements in PHP
if…else statement
Use this statement when there are only two options or outcomes
Syntax
1
2
3
4
5
6
7
|
if (condition)
//Code to be executed if condition is true
else
//if condition is false, execute this block;
|
Example:
1
2
3
4
5
6
7
8
9
10
11
|
<?php
$name = "mike";
if ( $name == "mike" ) {
echo "Your name is Mike!<br />";
}
?>
|
To execute more than one lines in true or false situation use curly braces as below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?php
$d=date("D");
if ($d=="Sat")
{
echo "Hi!<br />";
echo "It weekend,";
echo "Lets meet up!";
}
?>
|
Using Else:
1
2
3
4
5
6
7
8
9
10
11
|
$Num = 3;
if ( $num == 3 ) {
echo "The if statement is true";
} else {
echo "The if statement is false";
}
|
elseif statement
Use this option where you have more than 2 situations to execute code.
Syntax
1
2
3
4
5
6
7
8
9
10
11
|
if (condition)
//Code to be executed if condition is true
elseif (condition)
//Code to be executed if condition is true
else
Execute if none of above conditions are true
|
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<?php
$day_today=date("D");
if ($day_today =="Fri")
echo "Have a nice start of weekend!";
elseif ($day_today =="Sat")
echo "Weekend in full move!";
elseif ($day_today =="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice working day!";
?>
|
Switch Statement
Use this option when you have many options and have to execute one of those. Go to this page
Leave A Comment?