PHP Tutorial – Part 3

PHP Tutorial – Part 3

PHP Tutorial: Introduction

Over the past two parts I have shown you the basics of text in PHP and how to store it as variables. In this part of the tutorial I will show you how to use IF statements to make decisions in your scripts.

PHP Tutorial: The Basics Of ‘IF’

If statements are used to compare two values and carry out different actions based on the results of the test. If statements take the form IF, THEN, ELSE. Basically the IF part checks for a condition. If it is true, the then statement is executed. If not, the else statement is executed.

PHP Tutorial: ‘IF’ Structure

The structure of an ‘IF’ statement is as follows:

IF (something == something else)
THEN Statement
} else {
ELSE Statement

PHP Tutorial: Variables

The most common use of an IF statement is to compare a variable to another piece of text, a number, or another variable. For example:

if ($username == “webmaster”)

which would compare the contents of the variable to the text string. The THEN section of code will only be executed if the variable is exactly the same as the contents of the quotation marks so if the variable contained ‘Webmaster’ or ‘WEBMASTER’ it will be false.

PHP Tutorial: Constructing The THEN Statement

To add to your script, you can now add a THEN statement:

if ($username == “webmaster”) {
echo “Please enter your password below”;

This will only display this text if the username is webmaster. If not, nothing will be displayed. You can actually leave an IF statement like this, as there is no actual requirement to have an ELSE part. This is especially useful if you are using multiple IF statements.

PHP Tutorial: Constructing The ELSE Statement

Adding The ELSE statement is as easy as the THEN statement. Just add some extra code:

if ($username == “webmaster”) {
echo “Please enter your password below”;
} else {
echo “We are sorry but you are not a recognized user”;

Of course, you are not limited to just one line of code. You can add any PHP commands in between the curly brackets. You can even include other IF statements (nested statements).

PHP Tutorial: Other Comparisons

There are other ways you can use your IF statement to compare values. Firstly, you can compare two different variables to see if their values match e.g.

if ($enteredpass == $password)

You can also use the standard comparison symbols to check to see if one variable is greater than or less than another:

if ($age < “13”)

Or :

if ($date > $finished)

You can also check for multiple tests in one IF statement. For instance, if you have a form and you want to check if any of the fields were left blank you could use:

if ($name == “” || $email == “” || $password == “”) {
echo “Please fill in all the fields”;

Dedicated Server


Latest posts by Web Hosting UK (see all)


Leave your comment

Pin It on Pinterest

Share This

Please Share

Please be social and share this post with your friends!