If, else and elseif


In this tutorial you will learn how to use the following in PHP.
  • if
  • else
  • elseif


if


PHP Code
  1. <?
  2. $myname = "DanielXP";
  3. if($myname == "DanielXP") {
  4. echo "Your cool!";
  5. }
  6. ?>

"$myname" is the variable, I have set this as "DanielXP".
Line 3 is the if line, This gets the variable "$myname" and checks to see if it equals the other variable what i have also set as "DanielXP".

Notice: I have used two = signs in the if. If you don't use two then it would set the variable not check it.
As "DanielXP" & "DanielXP" are both the same, this script will output..

Your cool




else


Now lets have a look at the else.
PHP Code
  1. <?
  2. $number1 = 1;
  3. $number2 = 2;
  4. if($number1 === $number2) {
  5. echo "Weird, number 1 is the same as number 2!";
  6. } else {
  7. echo "Number 1 does not equal number 2.";
  8. }
  9. ?>


In this i have set to variables called "$number1" & "$number2" I have set each with a number.
The 4th line of the code is a if like i have explained above it checks to see if 1 equals 2, which it don't so we will move onto the else.

Output

Number 1 does not equal number 2.




elseif


Now last of all we can move onto the elseif.
PHP Code
  1. <?
  2. $number1 = 1;
  3. $number2 = 2;
  4. if($number1 === $number2) {
  5. echo "Weird, number 1 is the same as number 2!";
  6. } else if($number1 === 1){
  7. echo "1 is the same as 1!";
  8. }
  9. ?>


Same as above it checks the "$number1" & "$number2" variables, As 1 does not equal 2 it will move onto the second part which is the other if. As "$number1" is set as 1 this script will display...

1 is the same as 1!



Thats it for now i hope i have explained this.
DanielXP's Avatar
Author:
Views:
2,678
Rating:
Posted on Friday 4th April 2008 at 05:57 PM
Dalez
Dalez's Avatar
Thanks for this, as it has helped me alot!
Posted on Wednesday 21st March 2007 at 06:42 AM
paradox
paradox's Avatar
i thought with elseif your suposed to end it with an else. thats what a friend told me whos been codin awhile and its what iv been doin. corret me if im wrong please.