Introduction
The purpose of this article is to introduce you budding PHP programmers to the different types of variables that PHP provides. This article is aimed at complete beginners to PHP and programmers switching to PHP from another language.
What is a Variable?
A variable is like a container. It is used to store data in your application. For example, you could have a variable which holds a visitor's name, or perhaps a variable that contains a date.
Naming your Variables
In PHP, all variable names begin with the dollar sign ($) and can only contain letters, numbers and the underscore (_) character. They must begin with either a letter or an underscore. PHP has certain words that cannot be used as a variable as they are variables provided by PHP or reserved words. The variable $this would be a good example as it is defined by PHP.
PHP Code:
// Valid Variable Names
$myVar
$my_var
$__myVar
$_my_var_123
// Invalid Variable Names
$123
$my-var
$my var
$my.var
PHP Code:
// Good variable names
$username
$emailAddress
$postal_address
// Bad variable names
$a
$UsErNaMe
$padd70
Variable Types
PHP is a loosely typed programming language which means that any variable can hold any type of data. Compare this to the C++ programming language, and a number of others, where you have to declare a variable's type before it can be used. That variable can then only hold that type of data.
Although PHP variables can hold any type of data and convert it dynamically, we'll go over the types of data PHP supports here as it will come in useful.
Boolean
A boolean variable (commonly known as just Bool) is a variable that can only hold two values. It is either set to TRUE or FALSE.
Example:
PHP Code:
<?php
$logged_in = false;
$display_header = true;
Integer
An Integer (or Int) variable holds a number. Integer values range from -2,147,483,648 to 2,147,483,647 (although this can vary depending on your web server platform). Many programming languages support an unsigned integer which means that the value range goes from 0 - 4,294,967,295 but PHP does not.
An Integer variable must be a whole number (ie, no decimal points)
Examples:
PHP Code:
<?
$int1 = 123;
$int2 = -500;
$int3 = 2147483647;
Float
A float (or floating point number) variable also holds a number. The float range is much larger than an Integer's and like Integers it varies from platform to platform but the PHP manual says "a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is common". Floats also support decimal points in numbers.
Note: When you convert a number from a Float to an Integer, the number will always be rounded down.
Examples:
PHP Code:
<?php
$float1 = 12.34;
$float2 = 1.2e3;
$float3 = 100400.3840021;
String
This is probably one of the most common variable types that you will use. Strings hold all text data and can grow to any size. PHP has no specific in-built limitations on string size.
When assigning a string to a variable you need to enclose it in quotation marks. PHP allows you to use both single and double quotes when enclosing strings. However, there are some key differences between the two quote types.
- Single Quotes
When enclosing a string in single quotes PHP will not parse any control characters in your string (see below). You will also need to escape any single quotes and in your string using the backslash character.
If you enclose a variable within a single-quoted string it will not be parsed by PHP.
Examples:
PHP Code:
<?php
$name = 'Alan Wagstaff';
$story = 'Alan\'s a super guy!';
$message = 'Please open C:\\Windows on your computer';
- Double Quotes
Enclosing a string in double quotes allows you to use special control characters (see below). When using double quotes you will need to escape other double quote characters using a backslash (\).
Variables contained within a double-quoted string will be parsed by PHP.
Examples:
PHP Code:
<?php
$name = "Alan Wagstaff";
$welcome = "Welcome $name, have a good day!";
$html = "<label for=\"checkbox1\">";
- Special Control Characters
PHP provides several special escape sequences that can be used to manipulate strings. These control characters are as follows:
Code:
\n linefeed \r carriage return \t horizontal tab \v vertical tab \f form feed \$ dollar sign
- Escaping Strings
PHP provides the full stop operator to allow us to "escape" or break-out from strings. This is useful when using variables in strings.
Examples:
PHP Code:
<?php
$welcome = 'Hello ' . $name . ', welcome to TalkPHP!';
$simpleWelcome = 'Hello ' . $name;
Arrays
An array is a special variable that can hold multiple items that can then be sorted, added to, etc.
Example of a basic array:
PHP Code:
<?php
$myArray = array('Red', 'Yellow', 'Blue', 'Green');
There are two types of arrays, a numerical array and an associative array. A numerical array is accessed using numbers.
For example:
PHP Code:
<?php
$myArray = array('Red', 'Yellow', 'Blue', 'Green');
echo $myArray[0]; // would echo "Red"
echo $myarray[2]; // would echo "Blue"
Associative arrays allow for a second option when accessing them. They allow you to set a "key" for each item in your array which you can then use to access that item.
For example:
PHP Code:
<?php
$myArray = array(
'firstName' => 'Alan',
'lastName' => 'Wagstaff',
'email' => 'alan@example.com',
'age' => 27
);
echo 'Hello ' . $myArray['firstname'] . ', you are ' . $myArray['age'] . ' years old!';
The first thing you will notice is that we split our $myArray declaration over multiple lines. We could have put it all on the same line but it is much easier to read when spread over multiple lines. We have also made use of tabs to further improve the readability of it.
In our associative array you can see that we now have both keys and values. This allows us to add descriptive names to the array so we no longer have to remember what $myArray[3] was, we can now just use $myArray['age'].
Another thing to note is that arrays can take data of multiple types. In our associative array example we have both Strings and an Integer value.
Objects
An Object is another special variable type used in Object-Orientated Programming (OOP). An object is an instance of a class, a class being a self-contained block of code with its own variables and functions.
We won't go into details on Objects here as it would turn into a full-blown OOP tutorial but when you do start to learn Object-orientated programming, you will quickly grasp what Objects are.
Null
The Null variable represents a variable that has no value. You will most commonly use this when declaring your variables initially or when you want to remove a value from a variable.
A variable is treated as Null if it has not been given a value yet, it has been specifically set to Null, or you have used the unset() function on it.
Examples:
PHP Code:
<?php
$firstName = NULL;
$lastName = 'Wagstaff';
unset($lastName);
Conclusion
Hopefully this has given you a brief insight into the different types of variables that PHP has to offer. If you have any questions, feel free to come and visit us at TalkPHP - everyone there is happy to help
Further Reading
http://uk.php.net/variables
http://uk.php.net/types


Join the friendly bunch on IRC...