Login | Contact Us | Site Map | Resources

PHP Basics

Home > PHP Tutorial > PHP Variables

PHP Variables

Variables are PHP's method of storing values, or information. Once a variable is set, it can be used over and over again, saving you the work of typing in the value again and again, and allowing you to assign new values spontaneously.

Variables are identified by a dollar sign, immediately followed by a variable name. Variable names are case-sensitive, but you can name your own variables as long as they abide by four basic rules:

1. Variable names cannot contain spaces.
2. Variables names can contain letters (a-z and A-Z), numbers (0-9) and underscores (_).
3. Variable names can begin with letters or an underscore, but cannot begin with numbers.
4. Variable names should make sense so that you can remember them later!

Several examples of variables being assigned are below:

<?php
  $NonSensical_Variable_Name = "I am a variable value.";
  $empty_variable = "";
  $eyes = "brown";
  $hair = 'brown';
  $age = 35;
?>

As you can see, value is assigned to a variable using the "equal to" symbol, after which the value is declared. Numerical values do not require single or double quotes, but strings do in order to identify the beginning and end of each string. You will learn more about strings on a later page.

Most programming languages make you declare the data type of each variable that you set, but PHP automatically decides the data type of each variable for you, saving you the trouble of declaring each one. Any value set using single or double quotes will be a string, including numerical values. Numerical values set without using single or double quotes will be integers, which can be used to perform mathematical calculations, etc. There are eight different data types, including strings and integers, most of which we will learn more about later on.

If the whole point (why variables?!) is still fuzzy, don't worry, it will clear up quickly as we progress. In the meantime, don't forget to terminate each variable declaration with the ever-trusty semicolon!