BEGIN TYPING YOUR SEARCH ABOVE AND PRESS RETURN TO SEARCH. PRESS ESC TO CANCEL

Learn PHP: Class Two, Ifs And Elses

Moving on to PHP’s If Else Statements.

Here is one in action:

if ($condition) {
echo 'condition is true';
}

Simple enough? To start with as you can see you first write the statement name, in this case “if”. Then you enclose your condition in brackets, [A condition is essentially a question you ask PHP.] then you add an opening “curly bracket”. The opening curly bracket basically defines the start of the code to execute of the condition of the statement evaluates to true. In this case we are wanting PHP to output the text “condition is true” if the condition is true. Then finally we have a closing curly bracket.
In the above example the entire condition has simply been set to the variable $condition. Therefore what we are asking PHP is does the variable $condition exist, and if it does, does it have a value that is not NULL. [Null = Nothing, zero, zilch] In this case we didn’t actually define the variable $condition therefore the statement will evaluate to false and the code within the statement wont be executed. Therefore the above will output nothing at all. However the following code:

$condition = "Here!"
if ($condition) {
echo 'condition is true';
}

Would output “Condition is True”.

Now if statements are pretty useless on their own! What you really want is if / else statements, which we will look at here!

$condition = 10;
if ($condition == 5) {
echo "condition is 5";
}

Basically here the variable condition is 10. PHP Checks if it is 5. As we all know 10 is not 5, so PHP does nothing. However in this statement:

$condition = 10;
if ($condition == 5) {
echo "condition is 5";
} else if ($condition < 5) {
echo "condition is less than 5";
} else {
echo "condition is $condition";
}

We have an if statement, an if else statement and an else statement.
Basically the code explains it, but the condition is 10. If the condition is 5, PHP will output that it is 5. Otherwise if the condition is less than 5. PHP will output that it is less than five. Lastly, if nothing matches in the if or else if statements PHP will output its else. Saying Condition is 10.

A last sample before we head off.

$condition = "yes";
if ($condition == "no"){
echo "condition is false";
} else if ($condition == "yes"){
echo "condition is true";
} else {
echo "Something happened to the variable";
}

Here you can see that the condition is actually a word. PHP checks it just like it would a number and outputs all the same. Here PHP would output “Condition is True”.

And that’s it for today! Next week we have “arrays” so until then practice! 🙂

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked

This site uses Akismet to reduce spam. Learn how your comment data is processed.