![]() |
|
PHP If...Else...Elseif Statements. Free online PHP and MySQL Web Database Programming Tutorial... |
| Lessons | PHP If Statement |
|
|
• if • while • do while • for • switch • foreach • break • continue In this lesson we will discuss the if statement. The if statement in PHP is very similar to C, Java and Javascript. Often in our code we need to take decisions based on some conditions. The if statement is used when we want to execute some code based on some condition being true and not otherwise. Various flavors of if statements are available in PHP. 1. Simple if statement: We use this statement, when we need to execute a set of code when a condition is true. The syntax is as under: if (condition) code to be executed if condition is true; Code Example <html> <body> <?php $a = 10; $b = 20; if ($a==$b){ echo "$a and $b have the save values"; } ?> </body> </html> 2. if...else statement: We use this statement, when we need to execute a set of code when a condition is true and another if the condition is not true. The syntax is as under: if (condition) code to be executed if condition is true; else code to be executed if condition is false; Code Example <html> <body> <?php $day1 = "Friday"; $day2 = "Wednesday"; if ($day1 == $day2) { echo "Today it is ". $day1; } else { echo "Today it is not ". $day1; } ?> </body> </html> 3. if...elseif statement: We use this flavor of if statement when we want to execute some code if one of several conditions are true. The syntax is as under: if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Example Code The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice Sunday!" if the current day is Sunday. Otherwise it will output "Have a nice day!": <html> <body> <?php $d = date("D"); if ($d == "Fri") echo "Have a nice weekend!"; elseif ($d=="Sun") echo "Have a nice Sunday!"; else echo "Have a nice day!"; ?> </body> </html> Important Points 1. The PHP date("d") function used above returns the current day in three letters. 2. We can nest as many if statements as we need. 3. The if statement takes a condition. A condition is any expression, usually a comparision expression, that evaluates to a boolean true or false. 4. We can combine many conditions in if statements by using the logical operators, e.g. if (5 < 10 & & 10 > 4).
Next: PHP Do...While Loop
|