Forgot Password / Register
Site Statistics
Total Members: 510
Total Tutorials: 242
Newsest User: Hp
Todays Unique Hits: 121
0 Users 2 Guests Online

If, else and elseif

In this tutorial you will learn how to use the following in PHP.

  • if
  • else
  • elseif

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

"$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.
This script would display "You cool!" as "DanielXP" & "DanielXP" are both the same.

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


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.

This script will display "Number 1 does not equal number 2.".

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


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
Author:
Views:
1768
Rating:
Posted on Friday 4th April 2008 at 05:57 PM
Dalez
Dalez
Thanks for this, as it has helped me alot!
Posted on Wednesday 21st March 2007 at 06:42 AM
paradox
paradox
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.