Go to the menu - Go to the contents

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

Variables

Avatar
Author : M@teo21
Creation : : on 07/31/2007 05:34:42 PM
Last modification: : on 07/22/2008 03:39:53 PM
Rate and comment this tutorial
Print this tutorial
This is a very fundamental chapter!
Variables are essential elements in programming and therefore in PHP. It is not meant for twisted programmers but rather to simplify our lives. You cannot do anything without variables. :p

This chapter is a bit long so take your time to read it. For instance you can read one half today and save the rest for later. Read carefully because there are really important things to learn. Throughout this chapter, you will understand why PHP is so widely used !
Chapter Contents :
Previous Chapter Contents Next Chapter

What is a variable?

According to the meaning of the word, you should suspect it is something which changes all the time. Indeed the main feature of a variable is to be able to change its value. But strictly speaking, what does it mean?

A variable is a small piece of information stored in the memory temporarily. It has a short life cycle. In PHP a variable exists during the generation process of the page. Once the page has been generated, all variables are removed from the memory because they are of no use anymore. A variable is therefore not a file stored on the hard drive but a temporary piece of informaton.
Creating a variable is up to you, that is, you create it when you think it is needed.
What you should know is that a variable is made up of 2 things:

In this example, I used a variable called "age_of_visitor" with the value "17". The value of a variable can be changed at will and used for any calculations. And when we need it, we call it (by its name) and it tells us what it's set to. ;) It goes on like this: - Hey ! you age_of_visitor variable, what are you set at?
- 17.
- Thanks !
Variables may seem confusing for now but they will be mandatory for your PHP site. For instance, storing a username ("m@teo21") in a name_of_visitor variable, you will be able to use this information to display a personal welcome message like, " Hi m@teo21! welcome". You remember how to display a text in PHP, don't you? ;) The "echo" function you learned in the previous chapter will be very useful for practice!

Assign a value to a variable and display output

The first thing we are going to do is assign a value to the variable and then display what it contains.
In this example we are just going to create a variable and assign it a value just for the fun of it ^^ For example if we type:Code: PHP
1
2
3
<?php
$username_of_visitor = "Mateo21";
?>
We would create a variable:

Note that there is no spacing in names of variables. Instead, you can use an underscore sign _
Avoid using stresses, and any other symbols for names of variables. But for the value you are free.


We can notice several new elements. First the dollar sign ($): a variable's name always starts with this character. It actually tells PHP that you are using a variable. So anytime you see a dollar sign ($) it means there is a variable.
Then comes the equal sign (=): it obviously means that $username_of_visitor equals ...
Followed by the value. The value is enclosed in quotes because it is a text value.
Finally we have the semicolon sign (;), which ends the instruction.

Actually what would have the above code displayed?

Nothing at all :D unless you use the "echo" function. The server has just created a variable in memory, nothing else.

Now a variable does not only contains text. it can also be assigned numbers or booleans. Take a look at how to use them.

Bool-what? User image

Let me explain ^^
Remember that a variable can contain 3 different types of "data": text, numbers and booleans. This is how they are used.

To sum up: there are 3 types of elements in a variable, text numbers and booleans. Text is between quotes and for numbers and booleans, there are no quotes. Now that you've got this let's move on :D

Displaying the value of a variable



Now we are going to do a small experiment: use the echo function with variables. It is very easy as you will see.
Code: PHP
1
2
3
4
<?php
$username_of_visitor = "Mateo21";
echo "$username_of_visitor";
?>


What does it display? Wonderful, magic!! it displays Mateo21! :) Now try it by yourself to see if it works. Change the value of the variable in the first line and you will have something else displayed. It seems to be so simplistic, but you have to do it in order to understand the functioning of variables. The echo instruction is used to display the content of a variable, but you are not obliged to do so. Here is a very useful example: Code: PHP
1
2
3
4
<?php
$username_of_visitor = "Mateo21";
echo "Welcome $username_of_visitor !";
?>


You notice that the echo instruction has displayed our text with the $username_of_visitor inserted in. When the PHP page is generated, $username_of_visitor will display what it contains which in our case is Welcome Mateo21! You can now try by yourself and insert in your text the value of 1, 2, 3 variables... You will often need this easy technic in the next chapters, so practice it!

Working with numbers

Now, let's have your computer do some exercises. You will notice that arithmetic operations are just like a game. If you didn't know it let me tell PHP allows you to do arithmetic operations. Don't be scared because we are not going to do complex operations but just additions, substractions, multiplications and divisions. Not too difficult I hope? :p Here we are going to work on variables containing numbers only. Here are the symbols to know for calculations.

Operator description
+ Add two numbers together
- Substract the second number from the first number
* Multiply two numbers together
/ Divide the first number by the second


The rest is just a game.

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php
$number = 2 + 4; // $number takes value 6
$number = 5 - 1; // $number takes value 4
$number = 3 * 5; // $number takes value 15
$number = 10 / 2; // $number takes value 5
 
 
// Let's make it a bit harder
 
$number = 3 * 5 + 1; // $number takes value 16 
$number = (1 + 2) * 2; // $number takes value 6 
?>


Come on guys! This is not complicated. Check my calculations! As you can see, it's all easy :p You should not be scared to play with variables. Take a look at the following operations made with multiple variables.

Code: PHP
1
2
3
4
<?php
$number = 10;
$result  = ($number + 5) * $number; // $result is 15 
?>


This is pure logic and I can't tell you more. If you understand all these codes then you've made it and you are a professional of variables :D

Passing on variables between pages

Another interesting aspect of PHP is that we can use it to pass on variables from one page to another. You will see how useful it is for instance when passing on visitors names. I told you that once the page is generated, variables are removed. But how can we retrieve their value on another page?

Modify address during transfer


You have certainly seen this a couple of times but you have never asked yourself why some addresses were so long? For instance

http://www.mysite.com/infos.php?day=27&month=07&year=2003&title=Information

Well the answer is simple. It's because this is the place where your variables are and that's the way you can retrieve their value. :D

How does it work?

Well, this is pure HTML. As you already know, to create a link we use the <a> tag. For example:

Code: HTML
1
<a href="http://www.mysite.com/infos.php">Click here to access information !</a>


At the end of infos.php, use a question mark(?). Then write the name of the variable, an equal sign and the matching value:

http://www.mysite.com/infos.php?jour=27

This manipulation will create a particular type of variable: $_GET['day'] with the value 27 !
And if you want to create more variables, you just need to separate them by &. Note that in your HTML code you should not use the & symbol on your keyboard but instead use the corresponding HTML code &amp;
Look at the following example:

http://www.mysite.com/infos.php?day=27&amp;month=07&amp;year=2003&amp;title=Information

All the &amp; have been transformed into & by the visitor's browser.
In this case, four variables are created which correspond to the following instructions:

These variables seems a bit confusing but don't stop here! We are going to do a small experiment to see in practical terms what it is. We need 2 pages for that.




Code: HTML
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<p>
    Note that the second page only contains HTML. <br/> 
    Here are 3 links to the .php target page with variables that have different values:
</p>
 
<p>
    <a href="target.php?lastname=Dupont&amp;first name=Mike">Link.php?lastname=Dupont&amp;first name=Michel</a><br />
    <a href="target.php?lastname=Guichard&amp;first name=Patrick">Link.php? last name=Guichard&amp;first name=Patrick</a><br />
    <a href="target.php?lastname=Surret&amp;first name=Coralie">Liink.php?last name=Surret&amp;first name=Coralie</a>
</p>


Code: PHP
1
2
3
4
5
6
7
<p>Welcome!</p>
 
 
<p>Your last name is <?php echo $_GET['name']; ?> , and your first name is <?php echo $_GET['surname']; ?>.</p>
 
 
<p>Try again , <a href="call.php">click here</a> back to call.php</p>






So what do you think? Interesting isn't it? :D
You are now discovering a great aspect of PHP: the source code of .php target is very small, yet the page displays a different output everytime. The .php target page can display anything you want and you don't need to change its code!

Don't hesitate to do your practise by yourself so that you get used to this way of passing on variables. :)

Using a form to pass on variables.


There is also another practical way to pass on variables. You can do so by using a form (a form with text zones, cells, hits links etc.)

There is an entire chapter on forms in part III (I know we are only in the first part :D ). Forms cover a very wide domain and deal with some complicated things.
I don't want to confuse you, so we are going to see simple but useful things. :)

The simplest aspect is the text zone: User image
As you know, you can write anything in it. Our objective is to retrieve what the visitor has written.

We are going to follow the procedure we used before: a source .php page (with the text zone) and a target .php page (this page will display what you typed in)

Code: HTML
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<p>
    This page is only in HTML.<br />
    Enter your name: 
</p>
 
<form action="target.php" method="post">
<p>
<input type="text" name="first name" /> <input type="submit" value="Validate" />
</p>
</form>


Code: PHP
1
2
3
4
5
<p>Hi !</p>
 
<p>You are <?php echo $_POST['first name']; ?> !</p>
 
<p>If you want to change first name, <a href="call.php">click here</a> back to call.php</p>


To get a value from a form, we use the $_POST['xxxx'] prefix.
To get a value from an address ( as what we did) we use the $_GET['xxxx'] prefix.




You can now start playing with different names (Well I know you can find more funny games :p ). Ok let's be serious because what we are interested in is how it works?
The source .php page is a form. If you've read the chapter on (X)HTML you should know how to use it.

The only thing we can add is that "action" means "to display the .php target page". The name in the text zone is the variable's name. Here the tag is:

<input type="text" name="first name" />

Here the name of the text zone is "surname". In the target page, a $_POST['surname'] variable is created and the value is what you typed in. This is a different type of variable and I will not spend too much time explaining it here. You will understand later how it works, but right now you can start doing interesting things :)

Quiz

What symbol indicates the presence of a variable?

What is the output of the following instruction ?
Code: PHP - Show / hide line numbering
  1. <?php $my_variable = "Coucou !"; ?>

What is the output of this code?
Code: PHP
<?php
$name = "Pujol";
$surname = "Pierre";
echo "Your name is $surname $name";
?>

What is the correct $number ?
Code: PHP
<?php $number = (2 * 5 - 1) / 3; ?>
What is the $result ?
Code: PHP - Show / hide line numbering
  1. <?php
  2. $number1 = 2 + 6;
  3. $number2 = $number1 / 2;
  4. $result  = $number1 - (2 * $number2);
  5. ?>


If you feel you are having headaches, take some aspirin :p
This M.C.Q was harder than the others but at least it made you train your brain!
If you had all answers correct, congrats! You have picked everything and you have a logical approach which is very important in PHP

If you had problems understanding this chapter, don't hesitate to read it again; maybe within the next hours or the next days when you are more relax. :)

With the knowledge you have now you are ready for the next chapters. (these chapters are so easy compared to the one you've just read) You are now ready for the real and practical things. :D
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 8 Newbies Connected | SQL requests 10 Requests | Page loading delay 0.1063s (0.0949s)