PHP Variables

Variables are containers which hold values. This is useful when you need to use the same piece of information several times, or on several different pages, because it enables you to easily pass information between functions and documents, which is a big part of having a dynamic web page.

A variable is a name that you choose beginning with a dollar ($) sign. You set the variable with the assignment operator, otherwise known as the equals (=) sign.

$name = "Kali";
$age = 21;


You can then call on the variable later in the script. Here is an example.

<?php
$name = "Kali";
$age = 21;

print("Hi there, my name is $name. I am $age years old.");

?>
The script above will then print out: Hi there, my name is Kali. I am 21 years old.

When naming variables, make sure that it uses only letters, numbers and the underscore (_) character, and no spaces. It also cannot begin with a number, so $4bottles is not valid, but $four_bottles is. Remember that variable names are case sensitive.

So how would you use variables? A good example is with a HTML form that gathers user input, then uses that input on another page, like a guestbook does. Let's learn how to use a visitor's input here.