IF – ELSE
Probably you are already familiar with the “if construct” as already discussed in this tutorial. If not, please read it before you go on with this one
.
Well, with only the if construct you can perform already some really nice actions but we can go further with this. Really ? Yes, we are now talking about the “else” statement which actually tells the engine to perform some code if the expression is FALSE. Let’s take a closer look.
Example IF – ELSE
The below example should give you an idea of this kind of structure
if (expression)
{
// Code if TRUE
}
else
{
// Code if FALSE
}
Quite simple hea ?
Let’s take a look at the below snippet.
For the people here who don’t know what the function “strlen()” does…. It just returns the length of a string.
The result for strlen($var1) would be 21 and strlen($var2) would be 22, so there are not equal.
$var1 = 'This is just a string';
$var2 = 'This is another string';
if (strlen($var1) == strlen($var2))
{
echo 'The amount of characters are equal';
}
else
{
echo 'The amount of characters are not equal';
}
In the above example we use the comparison operator “==” (Equal) again, so we are checking if the length of both variables are the same.
As you already would guess, if the length’s are the same, the string “The amount of characters are equal” would be parsed to the clients screen. But they are not equal so the “else” statement will come in action right now as the expression will result in FALSE which indicates that the php engine must use the block of code after the else statement (if there is any off course). So it will
So the bottomline is that a IF – ELSE statement is quite usefull is you want to check a expression on it’s boolean value and if it’s true, perform block 1 and ELSE the other block of code!
Example 1
Here are some more examples of how to use the if – else construct.
if (5 != 6) // Results in TRUE
{
// Code if TRUE
}
else
{
// Code if FALSE
}
Example 2
if (5 > 6) // Results in FALSE
{
// Code if TRUE
}
else
{
// Code if FALSE
}
Example 3 (without accolades, so 1 line for each if or else)
if (5 > 6) // Results in FALSE // Code if TRUE else // Code if FALSE
Mail this!
- Comments (0)
- PingBacks (0)
- TrackBacks (0)


» Latest comments