Go to the menu - Go to the contents

[Site map] You are here --- > Newbies Paradise > Tutorials > Official > Website > Reading a tutorial

Conditions

Avatar
Author : M@teo21
Creation : : on 07/31/2007 05:38:01 PM
Last modification: : on 08/27/2007 01:56:37 AM
Rate and comment this tutorial
Print this tutorial
This chapter is very important because in PHP you will use conditional statements very often.
Nota : I should have called this chapter "conditionnal structures" but let's make it simple and use "conditions" ;)

What is the importance of conditions ?

Well, sometimes we need to display different things according to the data we have.
For instance, in the morning you need to say "good morning" and in the afternoon "good afternoon"

This is where conditions play a role. Depending on the case, PHP will execute different instructions. In our example we would say : If we are in the morning, display "good morning". Else, in the afternoon, display "good afternoon". You will see that conditions are the basis to make your website really dynamic i.e. display different things depending on the visitor, the time of the day, the date etc .

So let's go! :)
Chapter Contents :
Previous Chapter Contents Next Chapter

The basic structure: If......Else


We call it this way because it has a special structure.
The structure we are going to learn is the simplest one. Fortunately for us, we don't have 50 ways of using conditions otherwise it would have been very hard :p

To study the If ...Else structure we are going to proceed as follow:
  1. Symbols to know : there are symbols you must know which are used for comparison and are useful for conditions.
  2. If...Else structure : that's the bigger part of it. Here you will understand how anf If ...Else statement works and you need to understand it very well ;) .
  3. Multiple conditions : this one is a bit hard and you will see that we can use several conditions at the same time.
  4. Booleans : there is a special way of using conditions when working with booleans. Refer to the chapter on variables for the definition of booleans.
  5. Bonus : there is always a bonus for those who follow well and thorougly :p .


Symbols to know



Before we start let me give you a table of the different symbols we are going to use. Try to memorise them as they are very useful.

Symbol Meaning
== Equals
> Bigger than
< Smaller than
>= Bigger than or equal to
<= Smaller than or equal to
!= Different from

There are two "equal" symbols on the first line. You should not confuse with the single sign we saw in the chapter on variables. In this case this sign is used to test equality i.e. "if it's equal to"

The symbols "Bigger than" (>) and "smaller than" (<) are located on the lower left corner of the keyboard


If... Else structure



Here is the structure of a condition:

Here is an example:

Code: PHP
1
2
3
4
5
6
<?php
if ($age <= 12)
{
echo "Hi kid!";
}
?>


Here we tell PHP : To display "Hi kid!" if the $age variable is smaller than or equals 12.

Notice that in most cases, the condition concerns a variable.
In our example, our variable is the $age. What is important in conditional statements is that there are two possibilities: either the condition is true (age is small than or is equal to 12) and something is displayed or the condition is not true and there is nothing displayed.

Well, let's improve our example. We are going to display something if age is bigger than 12:

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?php
$age = 8;
 
if ($age <= 12) //  If age is smaller than or is equals 12
{
echo "Hi kid! Welcome on my website!<br />";
$permission_enter = "Yes";
}
 
else // 
{
echo "<This is a website for kids, you are too old to enter. Bye!<br />";
$permission_enter = "No";
}
 
echo "Do you have permission to enter? The answer is: $permission_enter";
?>


How does the code work? First of all I put several instructions between quotes (you can put as many as you want)
Then you notice the word "else" that I added. It simply means the following: if age is less than or equals 12, do this,or else, do that.

Try this code and change the value of $age. You will see that the message displayed depends on the value you give to $age!

Obviously, you can put the instruction you want between quotes. Here for instance, I displayed a message which depends on the value of $permission_enter. Take a look!

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?php
if ($permission_enter == "Yes") // IF we have permission
{
// instructions to execute if we have permission
}
 
elseif ($permission_enter == "No") // ELSE IF we do not have permission
{
// instructions to execute if we do not have permission
}
 
else // ELSE (variable do not contain Yes or NO, so there is no result)
{
echo "Euh, I don't know your age could you remind me please?";
}
?>


Well, It's getting a bit difficult, isn't it? :p

Well the new element here is the keyword Elseif. This is the order in which the conditions appear:
  1. If $permission_enter is "Yes", execute the instructions...
  2. Else if $permission_enter is "No", execute different instructions...
  3. Else, ask the age again to know if permission is granted or denied.

At the begining a variable does not contain anything. Its value is empty and we use the word "NULL"
To check if a variable is empty, write: if ($variable == NULL)...


Multiple conditions



You must be wondering: "What weird thing is he going to talk about again?" :D

Well, we can always make things a bit harder, so you must be used to it now ^^
Multiple conditions are very useful, so that's why I couldn't miss the chance to talk about them! Just a small effort guys! :)
What we are going to do is give several conditions at the same time, and for that we need new keywords:
Keyword Description Equivalent symbol
AND And &&
OR Or ||


The equivalent symbol of OR are two vertical bars (shortcut Shift backslash):p

In the first colon there is the keyword and in the third, its equivalent symbol. You can use both, but I advise you to use the keyword. You can use these keywords to write several conditions like in the following example.

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
if ($age <= 12 AND $sex == "boy")
{
    echo "Welcome on the website of Captain Megakill !";
}
elseif ($age <= 12 AND $sex == "girl")
{
    echo "This is not a site for girls, go play with your dolls !";
}
?>


It's very simple and easy to understand: if age is less than 12 and i's a boy, access is granted.
Else, if it's a girl and she's less than 12 well! We just tell her to go play somewhere else! Sorry girls, that's just an example. :p ).

Ok let's see a last example with or and we stop! ;)

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
if ($sex == "girl" OR $sex == "boy")
{
    echo "Hi Earthman !";
}
else
{
    echo "Euh, if you are not a boy or a girl then who are you?";
}
?>


Booleans



If you take a look at the last source code (permission_enter) don't you think it is better to use booleans?
We talked about booleans in the chapter on variables, do you remember?
These are variables which are either true or false. Booleans are very useful with conditional statements. Take a look at how they are used.
Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
if ($permission_enter == true)
{
    echo "Welcome little newbie! :o)";
}
elseif ($permission_enter == false)
{
    echo "You do not have acces !";
}
?>


Up to now it's ok! isn't it? I didn't put quotes for true or false (as I told you in the chapters on variables).
A great advantage of booleans is that they are really practical for conditions.
Why? because you don't need to add the == true. When you work on a variable, PHP understands what you mean.

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
if ($permission_enter)
{
    echo "Welcome little newbie :o)";
}
else
{
    echo "you do not have access !";
}
?>


PHP understands that it should check if permission_enter is true. Advantages :

If you read the first line indeed, you have: "IF we have access...".
It's therefore a shortcut to know when working on booleans.

It's true indeed but your shortcut does not work if we want to check that boolean is false, does it?

There is a symbol which enables us to check that, and it's the exclamation mark ! We write if (! $permission_enter)...
This is another way of doing things. But if you prefer you can write if ($permission_entrer == false). Both methods work, it's just a question of choice ;) .

The trick!



There is a small trick to learn on conditons.
Just know that both codes give exactly the same result:

Code: PHP
1
2
3
4
5
6
<?php
if ($variable == 23)
{
    echo "<strong>Congrats !</strong> You have found the mysterious word !";
}
?>


Code: PHP
1
2
3
4
5
6
7
8
9
<?php
if ($variable == 23)
{
?>
<strong>Congrats!</strong> You have found the mysterious number !
 
<?php
}
?>


As you can see we didn't use echo in the second colon. You just need to open a bracket ({), close the php tag (?>), and you can write the text you want to display in HTML!
This is very practical when you have a lot of texts to display, and to avoid all the backslashes before quotes (").
Don't forget to close the bracket after (inside the php tag of course).
Well, there's nothing special to learn after, except that you will always meet conditions in all examples that I will give you later on.
You should not have problems using conditions. You just need to repeat the examples I gave you for the IF ...Else structure and apply it to your own example. Don't worry because we will get time to practise and you will find conditional statements essential.

An alternative step: Switch

AN ALTERNATIVE STEP: SWITCH

In theory, if... elseif... else are enough for conditions.

But why do you want to complicate things with a new element? User image

To show you the importance of Switch, let me take the following if ......elseif...else example.
Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
if ($note == 0)
{
    echo "You are a real newbie !!!";
}
 
elseif ($note == 5)
{
    echo "very bad";
}
 
elseif ($note == 7)
{
    echo "bad";
}
 
elseif ($note == 10)
{
    echo "just the average...";
}
 
elseif ($note == 12)
{
    echo "quite good";
}
 
elseif ($note == 16)
{
    echo "very good!";
}
 
elseif ($note == 20)
{
    echo "Excellent job it's perfect !";
}
 
else
{
    echo "Sorry, there's no message for this mark";
}
?>


Let me tell you straight that this is a simplified example taken from the PHP script I wrote for the MCQ ;) .
As you can see, it's heavy, long and repetitive. To avoid that, we can use Switch.

Take a look at the same example with Switch (the result is the same but the code is better)

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
$mark = 10;
 
switch ($mark) { // indicates our variable
case 0: // when $mark equals 0
echo "You are really a big newbie !!!";
break;
 
case 5: // when $mark equals 5
echo "very bad";
break;
 
case 7: // when $mark equals 7
echo "bad";
break;
 
case 10: // etc etc
echo "just the average...";
break;
 
case 12:
echo "quite good";
break;
 
case 16:
echo "very well !";
break;
 
case 20:
echo "Excellent job, perfect !";
break;
 
default:
echo "Sorry, no message for this mark";
 
}
?>


Test to code !
Try to change the mark (first instruction) to see how PHP reacts! And if you want to edit this code which is not that perfect, you can. It will be a kind of practice for you!


You can notice that there are less brackets (just at the beginning and at the end of Switch)
When using switch, we have to indicate at the beginning the variable we are going to use (in our case $mark). We tell PHP : I am going to analyse the value of $mark. After that we use "case" to anlyse every situation (case 0, case 10 etc etc...). It means: <Case when value equals 0... Case when value equals 10...

Advantage: no need to use two equal symbols! Disadvantage: it does not work with other symbols (< > <= >= !=). Switch only tests equality.

The keyword "default" at the end is somehow equivalent to "else". It is the default message independent of the value of the variable.

There is one important thing to know: let us suppose that in our example, the mark is 10. PHP will read: case 0? no; case 5? no; case 7? no; case 10? yes I execute instructions. But unlike the elseif, PHP does not stop to 10 and continues to read the following cases! :waw: case 12, case 16 etc...

To prevent PHP from doing that, use the break; instruction. The "break" instruction asks PHP to exit Switch. When PHP meets break, it exits the brackets and cannot read the following cases.
Try to remove the break from code 1.6.7, and you can see how important they are!

When shall we use if, and when shall we use Switch ?

It is more for a purpose of presentation and clarity. For a short condition, we use If and for a series of conditions we use Switch :)

Quiz

Conditions make it possible to ...
Which of the following symbol means "is different from" ?
What is the output of this code ?Code: PHP
<?php
$result = 25 - 10;
if ($result < 15)
{
    echo "you lost";
}
else
{
    echo "you won";
}
?>

can the following code display "day" ?Code: PHP
<?php
if ($text != "Menu")
{
    echo "Night";
}
elseif ($text == "Menu")
{
    echo "Evening";
}
else
{
    echo "Day";
}
?>

Which one is the animal at the end of the code ?Code: PHP
<?php
$length = 145;
$width= 73;


if ($length > $width AND $lwidth > 100)
{
    $animal = "Parrot";
}
elseif ($length > $width OR $width != 73)
{
    $animal = "Snake";
}
else
{
    $animal = "fox";
}
?>

What is the output of this Switch ?Code: PHP
<?php
$country = "Spain";
switch ($country)
{
case "France":
echo "Salut";
break;
case "UK":
echo "Hello";
break;
case "Spain":
echo "Hola";
break;
}
?>


Let me tell you that even if you seem not to notice, you are learning the very basics of PHP programming which will determine your style when you write script.
We can talk about programming style because every programmer will present his code differently ( the result is always the same but the steps are very different)
In this chapter, maybe did you notice my style! You will also create your own style step by step ^^

Something is sure, you are now learning most of the things you need to know, and you need to hang on because it is almost the end of this tutorial on the basics of PHP!
Previous Chapter Contents Next Chapter
Author : M@teo21
Rate and comment this tutorial
Print this tutorial

Change your template | Learn more about NP | Site map | Terms of use | Rules | RSS feed | XHTML 1.0 | CSS 2.0
Powered by Simple IT SARL: Contact us

There is nothing else to read, you have to go up now !

Do you want to be published here? Contact us.

Number of Newbies connected 6 Newbies Connected | SQL requests 10 Requests | Page loading delay 0.0976s (0.0862s)