TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Advertisement
Variables for Beginners
   Variables for Beginners


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 
You should always try to make variable names as descriptive as possible. Whilst holding the visitors name in a variable named $n may make sense to you when you are writing the script, it's unlikely to do so when you look back at the code a year down the line. A better example of a variable would be $name or $fullName.

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';
Notice in the second example how we had to escape the single quote to prevent PHP thinking that we had ended our string. In the third example, we have to escape the backslash character. This is to prevent PHP thinking that we where trying to escape the W character.


- 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\">";
In the second example you can see that we have included the $name variable in our string. PHP will parse this variable so assuming the $name variable contained "Alan", the $welcome string would become "Welcome Alan, have a good day!". In the third example we have to escape the double quotes used within the HTML to prevent PHP thinking that we have ended our string.


- 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');
As you can see in this example, we use the array() function to create our new array and assign it to the $myArray variable. In this example, we added four items to the array when we created it; the colors Red, Yellow, Blue and 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"
As you can see, we use square brackets after the variable name to tell PHP which array entry (or Index) we wish to use. Array indexes in PHP always start at zero so in our example above, echoing $myArray[0] would echo Red, and echoing $myArray[2] would echo Blue. If you tried to use an index that didn't exist (eg, echo $myArray[15]) you would receive a PHP notice telling you that the index does not exist.

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!';
While this example may look more complicated it is essentially the same as our last one.

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);
In this example, we set $firstName to Null, then use the unset() function to make $lastName Null.


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
Report this Article
Last 5 Article Reviews Read All Reviews
   Nice read!
Review added by Norman on 02-14-2008
Nice article.
I have not understand what are
Integer and Float..
Anyway, it's a good article. Thank for writing it.
   A good way to start
Review added by ReSpawN on 01-21-2008
One of the more simple articles, but yet very fully explained. Not to show off, but it doesn't apply to me anymore. Still, I would recommend this article to people who are still in the learning progress! Once again, nice work Alan!

All times are GMT. The time now is 11:53 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design