Variables


Variables are a way of storing information. They can vary, from storing integers, strings, functions, boolean, etc.
Rather than having to write, and re-write, and re-write a particular piece of information, we can assign it to a variable which we then call upon over and over.
Here's how you declare a variable:

$variable = "Hello World";

All variables start with $ and without it your variable will not work.
They are cAsE-sEnSiTiVe.
ie: $myName is different from $myname
Variables have to start with a letter, or an underscore.

$age = 19; // correct
$19 = 19; // wrong

They can only have alpha-numeric values, including underscores.
$my^name# = "Kalob"; // wrong
No spaces are allowed. You can camelCase them, or use underscores.
$my name = "Bob"; // wrong, it has a space
$myName = "Bob"; $my_name = "Bob"; // these two are correct

One great advantage that PHP gives us, over some other types of languages, is that you can declare a variable out of anywhere.

Numbers and Strings:
A variable with a value of a number only, does not need to be enclosed by quotes.
$age = 19; // this is correct
$age = 19.5; // this is correct
$age = "19"; // also correct
$age = age19; // wrong, it has letters.
Strings need quotes every time.
$str = "Hello World"; // this is correct
$str = Hello World; // this is wrong

A good rule of thumb for variables: Don't quote numbers, quote everything else.

Note:
If a variable is declared, and the same variable is declared after it, the newest one takes possession.
Example:

<?

$hello = "Hello World";
$hello = "Hey there, how are you?";

?>

The output would be:


Hey there, how are you?


echo'ing a variable:
You can echo a variable like a string.
Quick example:

<?

$age = 21;
echo "I am $age";

?>

We'll learn in the Strings page.

Task Discussion