PHP if statement


Home - Tutorials - Basics

In this tutorial I will show you how to use the if statement in PHP.

Tutorial info:


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

Bookmark PHP if statement



Bookmark and Share

Step 1 - Control structures


PHP if statement


Control structures are the fundamental elements of PHP (and any other programming language). These structures allows you to controll the program / script flow. In PHP there are more control structures and we can split them into 2 categories.

In this description I will focus only on the if statement which is maybe the most important conditional statement.

You can use the if statement if you want to execute a set of code when a condition is true. It is very similar as in C. The syntax is the following:

if (condition) code to execute in case the condition is true;

Let's see a real example.
Code:

if ($userName == 'Peter') echo 'Hello Peter!';
 
Notice that we used == in the condition and not =. This means that we want to check the equality og the left and right values and we don't want to assign a new value to the variable.

In this example there was only a one line statement to be executed if the condition is true. Of course you can use a complete code block. In this case you have to put all relevant code in a code block separated by { and } as follows:
Code:

if ($userName == 'Peter') {
echo 'Hello Peter!';
echo 'Nice to see you again!';
}
 





Next Step of PHP if statement


Tags: php if statement, if statement, if, php



Follow phpf1 on Twitter




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

Total time: 0.0107