Saturday, August 16, 2008

PHP if else statement - The if-elseif-else statement

In the previous tutorial you have learnd how to use the if statement in PHP. However that post only shows the very basic syntax of this powerfull control structure. Now you will learn how to use more complex branching.
In the previous tutorial we used the following code:

Code:


$userName = 'Peter';
if ($userName == 'Peter') {
echo 'Hello Peter!';
}

PHP F1



However what if the user is not Peter and we want to display an other message in this case. Of course you can do this. Here comes in the else statement which is an integral part of the complex if-else control structure.

Let's see how to use it:



Code:


if ($userName == 'Peter') {
echo 'Hello Peter!';
echo 'Nice to see you again!';
} else {
echo 'Hey, you are not Peter!';
echo 'Who are you?';
}

PHP F1



As you can see the syntax is quite easy. If the user is Peter then the first code block will be execute if not (else) then the second one.

Of course we can extend it a bit more.



Let's suppose you want to differenciate a bit more as before. For example you want to greet not only Peter but Max as well. In this case you have more options. You can do it in one if - else statement like this:



Code:


if ($userName == 'Peter' || $userName == 'Max') {
echo 'Hello Peter or Max!';
echo 'Nice to see you again!';
} else {
echo 'Hey, you are not Peter or Max!';
echo 'Who are you?';
}

PHP F1



However in this case tha same code is executed for both Max and Peter. Of course you can write 2 if statements one after another as follows:



Code:


if ($userName == 'Peter') {
echo 'Hello Peter!';
echo 'Nice to see you again!';
} else {
echo 'Hey, you are not Peter!';
echo 'Who are you?';
}

if ($userName == 'Max') {
echo 'Hello Max!';
echo 'Nice to see you again!';
} else {
echo 'Hey, you are not Max!';
echo 'Who are you?';
}

PHP F1



If you run this code you will see that it is still not the best sollution. As in this case if the user is Max then he first get a message that he is not Peter and only after that get a wilcome message. So to solve this problem the best sollution is to use the if - elseif -else 3 parts statement as follows:



Code:


if ($userName == 'Peter') {
echo 'Hello Peter!';
echo 'Nice to see you again!';
} elseif ($userName == 'Max') {
echo 'Hello Max!';
echo 'Nice to see you again!';
} else {
echo 'Hey, you are not Peter nor Max!';
echo 'Who are you?';
}

PHP F1

No comments: