If/Else/Else If Beginners Tutorial
Posted by Pete | Posted in PHP Beginners, PHP Tutorials | Posted on 03-10-2009-05-2008
0
After contact from some visitors starting to learn PHP. I am going to be writing a few tutorials on the basics of PHP. In this tutorial we will cover how to use the If Statements.
If statements are used to check if something matches something else. The syntax for a simple If statement is as
if(statement){ // if statement matches run any code here }
If it doesn’t match then ignore.
In statements we may need to use expressions below is a list of some of the most common expressions.
== Check if statements match
!= Check if statements do not match
< Check if statement 1 is smaller than
<= Check if statement 1 is smaller than or equals
> Check if statement 1 is bigger than
>= Check if statement 1 is bigger than or equals
So now we have some expressions lets see how we can use all this.
<?php $var1 = "foo"; if($var1 == "foo"){ echo "Var1 equals foo"; } ?>
The example sets $var1 to foo then in the if statement it checks if $var equals “foo” and if it does it displays a success message. But how do we display an error message if the statements do not match, this is where the else comes into play. In the next example we will show how to use if and else.
<?php $var1 = "foo"; if($var1 == "foo"){ echo "Var1 equals foo"; }else{ echo "Var1 doesnt equal foo"; } ?>
Now we are able to display both a success message and an error message in case the statements do not match. So now we’ve got both if and else but what happens if we need to put both together and create a else if statement. Else If statements are used to check multiple statements. It is used to check if the first statement is correct and if not it moves onto the second if statement.
<?php $var1 = "foo"; if($var1 == "foo"){ echo "Var1 equals foo"; }else if($var2 == "boo"){ echo "Var2 equals boo" }else{ echo "none match"; ?>
So that is the end of the if/else/else if tutorial. We have covered some of the basics on if statements. If you have any further questions please leave a comment below and myself or other members of the community will get back to you.


