The else statement as a concept is very easy to understand and straight forward. This statement is used in combination with the IF statement and what it does is extending the if statement. You use “else” when you want to run a piece of code when the condition of the “if” is not met.
<?php
$number = 10;
if ( $number == 10)
{
echo “The number is”.$number;
}
else
{
echo “The number is not equal with 10”;
}
?>
After you write the above code you can play with the value of the variable $number and see what happens, as you can see it’s not so difficult to understand the concept behind it.
Now it’s time to show you the elseif / else if statement, this statement is just a bit more difficult because with it you can chain multiple conditions and the program will run the code for the first condition that is true in the chain. I know that at first this can be a little confusing but with a little bit of exercise you will understand it.
<?php
$number = 10;
if ( $number == 10 )
{
echo “The number you have chosen is 10”;
}
elseif ($number == 12)
{
echo “The number you have chosen is 12”;
}
else
{
echo “The number you have chosen is “.$number;
}
?>
As you can see in the example from above, between the else and the if statements there is an elseif statement, this means that the program will check between these three conditions and will choose to run the code from the one that is true based on the value that the $number has.
I know, maybe it’s a bit confusing at first but try a few of these exercises of your own and you will get the hang of it in no time, maybe even paste them in the comments, i would be glad to see with what you have done.
Cheers