Conditionals and Looping
In the previous chapters the basics of PHP have been explained. With this you must be well versed with the basic idea of PHP. Now we will be taking a step forward and moving on to the learning of the conditional statements and looping structures. These conditional statements and looping structures give you more flexibility in writing a PHP script.
Conditional Statements
Conditions and conditional statements are a part of every programming language and scripting language. There are times when you want to perform different actions for different decisions. In this you have to use conditional statements, so that the correct decision should be made.
Consider a situation if you want to greet every visitor on your site on 25 th December with Merry Christmas. In order to achieve this you do not have write a code on Christmas displaying Merry Christmas. This can be done well in advance as you can always write a conditional statement that if date is 25 th December then Merry Christmas should be displayed. So, with the help of conditional statements job done, well in advance.
In PHP there are two conditional statements:
- If then else statement – This statement is used to execute a specific set of code if the condition is true and other set of code should be executed if the condition is false.
- Switch statement – This statement is used when you want that one of many lines of codes should execute.
If Statement
The “if else” statement is used if one set of code has to be executed when the condition is true and another set of code has to be executed when the condition is false.
Syntax |
If (condition) Statements to be executed if code is true; else Statements to be executed if code is false; |
In the following example x is compared with y. If x is greater than y then it will display x is greater then y else it will display y is greater than x.
Example |
<html> |
<body> |
<?php |
$x=10; |
$y=15; |
if ($x>$y) |
echo "x is greater than y"; |
Else |
echo "y is greater than x"; |
?> |
</body> |
</html> |
In the if statement if you want to execute more than one line when the condition is true then those lines should be put in curly braces.
No comments:
Post a Comment