PHP if else statement


Home - Tutorials - Basics

In this tutorial I will show you how to use a bit more complex control structure if - elseif - else in PHP.

Tutorial info:


Name:PHP if else statement
Total steps:2
Category:Basics
Level:Beginner

Bookmark PHP if else statement



Bookmark and Share

Step 1 - The if - else statement


PHP if 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!';
}
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?';
}

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.





Next Step of PHP if else statement


Tags: php if else, if else, php, if, else



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
CSS F1
Database F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0219