The if/else statement
Has any ever said to you “if you work hard, then you will succeed in whatever you do”? And then what happens when you don’t work hard?, Well, you will fail it’s as simple as that. This is an example of an if/else statement.
- If you work hard then you shall achieve whatever it was that you had set out to do.
- Else, if you don’t work hard, then you will fail and shall not be rewarded for your lack of effort.
How does this translate into something that is useful for the
php developers? Well think about this for instance:
Someone comes to your website and you want to ask this particular visitor if this is their first trip to your website. With an if statement this is easy enough to do. Simply have a statement to check off, “are you visiting this webpage for the first time.” If the condition statement is true then have them directed to the “insert your name” page, else let them view the website as they normally would because you have already asked them for their name in the past.
If/else an example
Using these statements can add new layers of “awesome” to your website.
Here are the basic forms of an if/else statement in php:
$number_three = 3;
if ( $number_three == 3 ) {
echo "The if statement evaluated to true";
} else {
echo "The if statement evaluated to false";
}
Display:
The if statement evaluated to true
This is a lot to handle in just one sit down reading, so let’s step through this code, piece by piece:
- We first made a PHP variable called $number_three and set it equal to 3.
- In this example we compared a variable to an integer value. To do such a comparison we use "==", which in English means «Is Equal To».
- $number_three is indeed Equal To 3 and so this statement will evaluate to true.
- All coding that is contained between the open curly brace which looks like this “ { “ follows the if statement and the closed curly brace that looks like this “ } “ will be used for when the if statement is true.
- The code contained within the else segment will not used.
Execute else code with false
On the other hand, if the if statement was false, then the code contained in the else segment would have been executed. Note that the code within the if and else cannot both be executed, as the if statement cannot evaluate to both true and false at one time! Here is what would happen if we changed to $number_three to anything besides the number 3.
PHP Code:
$number_three = 421;
if ( $number_three == 3 ) {
echo "The if statement evaluated to true";
} else {
echo "The if statement evaluated to false";
}
Display:
The code that contains the else statement will not be used.
The variable which was set to 421, which is not equal to 3 and the statement wasn’t true. As you can verify, the code statement within the else was used in this display.
Comments (4)
RSS Collapse / Expand-
davesteve12
andi
loopslike
Only Registered and authorized users may post comments