By now you should have figured that variables are just some “places” in which we store information, but what do we do with that information? I mean we need to do something with it and not just output it to the screen with the help of the browser and one of the most important thing we need to do with them is deciding what to do next if a condition is met like for example if x = 10, do something and that is a thing called conditional logic and by the way, you use it every day in your life, you make decisions based on conditional logic ( ex: what can happen if i cross the street without looking in the both ways before crossing, probably you will get hit by a car ). Basically this thing is about asking “what happens if”.
The same thing applies here too, conditional logic uses the word if followed by a condition that you ask to verify that something happens or not and if that condition is met, then something will happen ( something that you will tell the program to do ), this is the rough concept of IF statements.
Before testing this with a real example i want to tell you some things about comparison operators and make a small comparison between the assigning operators and the comparison ones.
As you know already, if you want to assign some value to a variable you use the equal (=) sign but if you want to compare two variables and check if they are equal you will use double equal (==). If you want to check if a variable is not equal to another you use exclamation mark and equal (!=); The grater and lesser signs they are used as they are ( <, >, >=, <=). You can find more info about operators here.
The basic syntax of the if statement is:
if ( condition)
{
do something
}
Now let’s see how this works with a real example:
<?php
$number = 10;
if( $number == 10)
{
echo “The number is equal with”.$number;
}
if( $number != 10 )
{
echo “The number is not equal with 10, the number is equal with”.$number;
}
?>
After you write this piece of code you can play with the number variable and assign to it different numbers to see the result, also you can make this example a bit more complex just by playing with concepts that were presented in the past tutorials.
Let me know with what you came up with in the comments.
Cheers.
One thought on “IF statement”