Using Variables In PHP

Variables are what make a dynamic web page dynamic. We can change variables on the fly with PHP. We can change their type from a string to an int to an array. There are multiple types of variables that we can use and we will get into those later.

Defining a variable

The first thing we must do is define our variable. This is very easy. All you need to do is add the following code to your php:

$variablename = value;
Notice the $ in front of the variable name? That tells PHP that this is a variable and has a value. It stores whatever you tell it to which is found after the single equals sign. Did you notice the ; at the end of the line? Remember that you need a semi-colon at the end of every decloration.

Using a variable

Now lets actually use a variable. Again we will use the Hello World! example. From this point forward, I will leave out the HTML code (unless it is needed) and just show you the PHP code that is important.

1. <?php 2.     $var = “Hello World!”; 3.     print “$var”; 4. ?>
Now to digest how this all works out. Line 1 and 4 are just the open and close tags. Line 2 sets a variable with the name of var, and sets the value to be “Hello World!”. Again did you notice the semi-colon? I can’t stress enough how many times I forgot to put the semi-colon in, and I get an error with my PHP script.

Line 3 does something a little different this time. Instead of just directly printing Hello World! it is printing the value of the variable. Because we put $var PHP understands that $var is a variable and will return the current value for it.