PHP Variables: The Ultimate Guide

Sep 19 2010 by Elias Zerrouq | 36 Comments

PHP Variables: The Ultimate Guide

Variables are important in every programming language — and it’s no different in PHP. Variables give developers the possibility of temporarily storing data to be used in PHP scripts (in PHP’s case, this happens in the server’s memory). This guide is all about working with variables in PHP.

By the way, if you are just starting out with PHP, I recommend reading this guide first: Learning PHP: Get Started Using PHP.

Comment, Comment, Comment!

Before we start, I’d like to introduce you to PHP comments. As a developer, you should try to comment your code in such a way that your code logic is explained well; this is one of the good habits coders should have.

PHP Variables: The Ultimate GuideWithout even looking at the PHP code, you know what this function is capable of just by reading the comments (in green).

How Does Commenting Work?

One way of placing a comment in one line is achieved by having two forward slashes (//) preceding the comment.

<?php
// This is a comment
echo 'Hello World!'; //This is another comment
?>

Another way to make comments is through a comment block which is wrapped by /* */. You want to use a comment block when your comment is more than a few lines long.

<?php
/*
By using a comment block, you are
capable of putting comments
on multiple lines.
*/
echo 'Hello World!';
?>

Another way — which is rarely used nowadays — is using a hash symbol (#) in front of the comment.

<?php
echo 'I\'m using comments!'; # An alternative syntax of commenting
?>

PHP and Variables

A PHP variable always starts with a dollar sign ($).This is just to let the PHP parser know that we are dealing with variables. You should always try to give your variables names that are as descriptive as possible.

Alphanumeric characters (i.e. A-Z, a-z, and 0-9) and underscores (_) are allowed, but the name cannot start with a digit. If your variable contains other characters or if it starts with a digit, it will produce a parse error.

<?php
// Valid
$player_name;
// Valid
$playerName;
// Valid
$_player_name;
// Not valid - has a space
$player name;
// Not valid - starts with a number
$1st;
// Valid
$player2nd;
?>

A variable name without a dollar sign ($) in front, or a variable name that contains invalid characters will most likely result in a parse error.

PHP aborts the parser on line 4 due to a parse error.

Assigning a Value to a Variable

A variable is useless if you don’t assign data to it! Assigning data to a variable is done like so:

<?php
$player_name = 'Freddy';
?>

We now have a variable called $player_name that contains a string value of "Freddy".

Printing Variables

We can print out a variable’s value using echo.

<?php
$player_name = 'Freddy';
echo $player_name;
?>

If you want to combine a variable with a static string, you can use a period (.) to append your strings together, like so:

<?php
$player_name = 'Freddy';
// Prints out "Hello Freddy!"
echo 'Hello ' . $player_name . '!';
?>

Alternatively, you can use quotes, which parses the string for the variable.

<?php
$player_name = 'Freddy';

// Prints out 'Hello Freddy'!
echo "Hello $player_name!"; 
// Prints out 'Hello $player_name!' because it uses single quotes
// thus $player_name is treated as a literal string
echo 'Hello $player_name!';
?>

Here are a few more examples of printing out variables, just to hammer in the concept.

<?php
$player_name = 'Freddy';
$player_friend = 'Tim';

// Prints out 'Hello Freddy! Is Tim still your friend?'
echo 'Hello ' . $player_name . '! Is ' . $player_friend . ' still your friend?';

$color = 'Blue';
$animal = 'Lion';
$text = 'I saw a ' . $color . ' ' . $animal . ' today when I was walking with '
         . $player_friend . ' and ' . $player_name;

// Prints out 'I saw a Blue Lion today when I was walking with Tim and Freddy'.
echo $text;
?>

About PHP Data Types

In most programming languages, the data type of a variable can only be defined once. In PHP, this is not the case. If you are working with PHP, you can’t define the type of a variable. It’s defined implicitly, which means that the data type will automatically be set for you depending on the type of data you assign the variable. This might sound confusing now, but later on, it will make sense, so just bear with me.

Null Data Type

The data type null refers to "nothing". Every variable that has no value assigned to it will be a variable of the type null. Null is exactly 0 bytes. Assigning null to a variable will delete the contents of that variable from memory.

<?php
// A variable without any value assigned to it, equals null
$player_name;
// Now $player_name is no longer null
$player_name = 'Freddy';
// $player_name is null again, and the string 'Freddy' has
// been deleted from memory
$player_name = null;
// $player_name is not null again
$player_name = 'Freddy';

// unset() is a PHP function that is the same as doing $player_name = null;
unset($player_name);
?>

Data Type Switching

Did you see what we just did up there? We jumped from a null data type to a string data type and then, all of a sudden, the variable was null again. No magic or hocus pocus involved, promise!

PHP is loosely typed, which means a variable is not restricted to just one data type. This means that you’re allowed to switch any variable between all the available data types without having to do anything. This is also referred to as type juggling.

However, I must note that type switching is expensive in resources — and can introduce potential points of logic errors in your scripts — and thus you should always try to keep your variables restricted to one data type if possible.

Use type juggling only when you really need to.

Bool Data Type

Bool is short for Boolean. It’s the smallest data type. A Boolean can only be one of two values: true or false.

<?php
$new_items = true; // There are new items available...
$has_permission = false; // Too bad you don't have the permission to read them!
?>

Note: Null, true, and false are words that should not be used in a variable assignment with apostrophes if you want to keep their functionality. See the code block below for clarification.

<?php

$new_items = true;

// This is not a Boolean! Just a string.
$has_permission = 'false';

// The $new_items variable doesn't exist now
$new_items = null;

// The $has_permission variable still exists, only the value has been changed 
// from 'false' to the string value of 'null'
$has_permission = 'null';
?>

About var_dump()

It’s time to talk about the var_dump() PHP function for a second, as it will help you greatly in debugging and learning more about your variables. This function shows you details about your variables, including what the contents of your variables are.

var_dump() is a function that will accept any expression. After processing the expression(s), the outcome and additional information about the result of the expression will be printed on the screen.

To keep things readable, it’s a good idea to always wrap a call to var_dump() between the <pre> HTML tag. This is not needed, but something that does improve readability of the output.

Tip: Passing multiple parameters to a function is done by separating them with a comma (,).

<?php
echo '<pre>';

$new_items = true;
// This is a string spelling the word 'false', it's not being treated
// as a Boolean
$has_permission = 'false';

// Make a call to var_dump() with the two variables above as the parameters
var_dump($new_items, $has_permission);

echo '<br>';

$new_items = null;
// This is a string spelling the word 'null', it's not being processed
// as the data type null

$has_permission = 'null';

// We've changed the variables, so let's do a check again
var_dump($new_items, $has_permission);

echo '</pre>';
?>

The following image shows a screenshot of the output of var_dump(). Notice that it tells you the data type, the size and the value of both variables. For example, $has_permission = 'false'; results in a var_dump of string(5) "false", which means that it is a string data type, that there are 5 characters, and that the string value is ‘false’.

Just like we expected.

As you can see, var_dump() is a very useful function. In the context of this PHP guide, it serves perfectly well to find out how type juggling works — but you’ll find it to be a great tool for debugging your PHP scripts.

Int Data Type

An int, which is short for integer, is simply a number. The maximum size of an integer is platform-dependent (meaning it depends on your web server’s operating system and settings), although a maximum value of about 2 billion is typical. If the server is a 64-bit platform, the maximum value is around 9e18.

Integers are always used to store numeric values. Because they are numeric, you can perform mathematical operations on them.

<?php
$number = 10;
// Take the current value and multiply by 10. $number is now 100.
$number = $number * 10;
// Same as above, but shorter. Now, $number is 1000.
$number *= 10;
// Add 5 to $number. $number is now 1005.
$number += 5;
// Same operation as above, just different syntax. $number is now 1010.
$number = $number + 5;
//Subtract 5. We are back at 1005.
$number -= 5;
// Subtract 5 again. We are now at 1000.
$number = $number - 5;
// Prints out 1000
echo $number;
// Still 100, we can assign the value using scientific notation
$number = 1e3;
// You are allowed to use binary. This equal to 37377 in decimal system.
$number = 0111001;
// An octal (equals 2 in decimal system)
$number = 0287;
// Negative numbers are allowed
$number = -2;
// Hexadecimal value (this is equal to 546 in decimal system)
$number = 0x222; 
?>

Float Data Type

Unlike integers, which have to be whole numbers, floating points can have decimals such as 12.3 or 6051.32179.

Examine and test the following code block to see how float variables work:

<?php
echo '<pre>';
$number = 10;
var_dump($number);
echo '<br />';
// Divide 10 by 6.
$number /= 6;
var_dump($number);
echo '</pre>';
?>

Our integer switched to a float data type by dividing it by 6.

A float has more precision than an integer but requires more storage space than an integer. The maximum size of a float is (just like an integer) platform-dependent. The maximum value is typically 1.8e308.

Floating Point Imprecision

The binary system (i.e. 1′s and 0′s), was not build for floating point numbers. That’s why simple decimal fractions like 0.4 and 0.8 cannot be converted to their binary counterparts without a small loss of precision. Keep this in mind when you are developing a web application that has to deal with a lot of floating point numbers.

String Data Type

If there’s one data type that you should already be familiar with, it’s the string because you’ve already seen it in action earlier. The string data type is the biggest data type PHP knows. The maximum size equals the size of the server’s memory. You should always take care that this size should not be exceeded (which is hard to do unless you’re intentionally trying to exceed it — but still, you should watch out).

We already covered combining regular text strings with variables and you also know what the difference is between using an apsotrophe (e.g. ‘string’) versus a quote (e.g. "string"), which was covered in the Learning PHP: Get Started Using PHP guide.

What we haven’t talked about are escaped characters. Remember how we took care of our indentation with \n and \t in the "Getting Started" guide? These are called linefeeds and they are categorized as escaped characters.

Read, analyze, and test the following code block to understand escaped characters in string variables. Also, check out this table to see a list of escaped characters in PHP.

<?php
echo "\tYou know what the output will be of this string.";

echo "\n\rThe special character '\\r' is new though.";

echo "\n'\\t' equals a horizontal tab, but '\\v' will result in a vertical tab.";

echo "\n'\\f' will output a form feed.";

echo "\nWhat if you want to use a regular dollar-sign (\$) in a string? We escape it! Like this: '\\$'.";

echo "\nSame thing for a double-quote (\"): '\\\"'"; 
?>

Type Casting

The last thing we’re going to cover in this PHP variables guide is type casting. Type casting is the name of the process in which a specific data type is transformed into another (e.g. switching from a string data type to an integer data type).

A few data types have their own function that takes care of casting other data types. You are able to cast almost every data type to another type by pre-pending the data to be cast by the name of the data type (e.g. (bool) $myString). Wow, that sounds complicated, but read the comments in the following code block and it will all become clearer.

<?php
echo '<pre>';
// Casting null to any other data type will result in the default value for 
// that data type (false, 0, 0 and an empty string)

// We start by converting an integer to null. You can replace the integer
// with any other data type.
$number = 15;

// Try using var_dump on $number to see what it comes up with.
$number = (unset) $number;
echo '<p />';

/* bool */
// Any other number besides 0 will be casted to true
$number_a = 0; $number_b = 3;
// false, true
var_dump((bool) $number_a, (bool) $number_b);
echo '<br />';
// When an empty string is casted to a Boolean, the result will be 'false'
$string_a = '';
// This value will also result in 'false', any other string 
// will result in 'true'
$string_b = '0';
// This will be casted to 'true'
$string_c = 'Hello World!';
// false, false, true
var_dump((bool) $string_a, (bool) $string_b, (bool) $string_c);
echo '<p />';

/* int */
// This will result in 1
$bool_a = true;
// ...and this will become 0.
$bool_b = false;
var_dump((int) $bool_a, (int) $bool_b);
echo '<p />';
// Floats casted to integers will lose their decimal precision and if they
// are bigger than an integer, the new integer will be the 
// maximal value. If you are casting a string to an int, as much integer data
// as possible will be casted
$string_a = '13 posts'; 
// Only the first two digits will be used
$string_b =  '45e2 liter';
//13 and 45000
var_dump((int) $string_a, (int) $string_b);

/* float */
// Casting strings and Booleans to a float works the same way as with integers.
// Casting an integer to a float will only change the data type. Nothing else
// will happen

echo '<p />';

/* string */
// Casting a bool to a string will result in '1' on true and '0' on false
// Integers and floats will be converted to their text counterparts
$number = 500;
// Will result in a string contain the characters '500'
var_dump((string) $number);
?>

Conclusion

In this guide, we learned as much as possible about commenting your code, variables, variable types and variable casting. If you have any questions, feel free to pose them in the comments.

Related Content

About the Author

Elias Zerrouq is a young web developer located in the Netherlands. He specializes in back-end development (PHP and MySQL) and classifies himself as a non-designing web developer (front-end development is okay though). Contact information can be found through his personal website.

36 Comments

Mark

September 19th, 2010

Great post for beginners. Looking at you last post I think it you will have a nice collection of posts for the budding web designer wanting to get more into programming.
Keep up the good writing!

dan

September 19th, 2010

good stuff, very useful

Kartlos Tchavelachvili

September 19th, 2010

Basic rules, well explained, Thanks

phpfarmer

September 19th, 2010

Thank you for your nice talk on code commenting. I really like it…

Phillip Harrington

September 19th, 2010

If you forget the $ before a variable, PHP usually tries to treat it as constant.

maroon

September 19th, 2010

Great and interesting article !

Daquan Wright

September 19th, 2010

Excellent stuff, didn’t get to read all of it but will later. Variables are so fundamental to programming, you can never study them too much!

Childmonster

September 19th, 2010

Great article for me and :)
Thanks

Satya Prakash

September 20th, 2010

To learn more about PHP and related technologies, subscribe to my blog. Thanks

huarong

September 20th, 2010

It’s difficult to write articles for beginners.
Great work!

Merlin

September 20th, 2010

Great article for beginners.

Thomas Tourlourat

September 20th, 2010

Just an other trick,

$first = “one”;
$second = “two”;
$third = “three”;

$varName = “first”;

echo $$varName; //Display “one”;

Can be useful.

David - Web Designer

September 20th, 2010

Thanks for posting, i didn’t know much about var_dump() before this. Look forward to the next one.

Jacob Gube

September 20th, 2010

@Thomas Tourlourat: Nice one!

Tim

September 20th, 2010

Good post. Very helpfull! But with a odd start: In the first suggestion I counted the word string about 7 times… not a good example of commenting…

webXpress-malta

September 20th, 2010

Really useful.. I know ASP and I just started learning PHP and I needed an article like this one :) THANKS

webXpress

September 20th, 2010

Nice article.. I just started learning PHP and something like this is very useful for me. Big thanks

gundisalvus

September 20th, 2010

(…)
// You are allowed to use binary. This equal to 37377 in decimal system.
$number = 0111001;
(…)

There’s a mistake, isn’t it? This is NOT binary, just octal, as in:

(…)
// An octal (equals 2 in decimal system)
$number = 0287;
(…)

cheers
g.

Elias

September 21st, 2010

@gundisalvus Not really. The binary numeral system only uses two numbers (1 and 0). The octal numeral system only uses the digits 0 to 7.

http://en.wikipedia.org/wiki/Binary_numeral_system
http://en.wikipedia.org/wiki/Octal

gundisalvus

September 21st, 2010

@Elias I know, I know… But if you do the conversions you will realise that there’s a mistake: 37377 in decimal is not 0111001 in binary but in octal!

0111001 in binary is 57 in decimal.

In PHP you specify that your integer variable is expressed in octal by putting a zero in front. But there is no way to express that it is expressed in binary, isn’t it?

Don’t think automatically that because a number has only digits 0 and 1 it has to be binary! I have 10 fingers (in decimal) but 10 hands (in binary) and 10 (in octal) are the sides of an octagon.

werew

September 21st, 2010

Thomas Tourlourat, Nice tips!! Tnx
And tnx for good article!

JT

September 21st, 2010

@Elias no, he’s right.111001 in binary would be 57. The only bases you can specify integers in explicitly in PHP are decimal, octal and hexadecimal. A number starting with 0 will be interpreted as octal unless the next character is x. Hence 0111001 is octal 37377. In binary, 37377 would be 15 digits long, and there’s no way to directly define an integer in php by writing it in binary

Dajve

September 21st, 2010

Just a quick note:

Stating “unset() is a PHP function that is the same as doing $player_name = null;” is inaccurate.

unset() will do exactly that – unset the variable and remove it from the variable scope, meaning that, whilst both will return null, a notice will be thrown any time the variable is accessed in the future.
This is especially important when dealing with variables assigned by reference. For example:

$foo = “a”;
$bar =& $foo;

// Example 1
$bar = null;
var_dump($foo); // outputs null

// Example 2
unset($bar);
var_dump($foo); // outputs (string)”a”

Dajve

Thibaut Allender

September 21st, 2010

@Thomas Tourlourat indeed, I wonder why it’s not in this guide, too advanced maybe ;-)

You could also mentioned this even more complex syntax:

$test1 = ‘foo’;
$blah = 1;
echo ${‘test’.$blah}; // returns ‘foo’

HTH

Dajve

September 21st, 2010

A couple of points as a follow-up to my previous post:

“// The $new_items variable doesn’t exist now
$new_items = null;”
is also inaccurate – the variable does exist, it is just null.

In the type-casting section, using (unset)$number to convert to null is valid but somewhat ill-advised considering the discrepancy between (unset) and unset(); and the fact that $number = (unset)$number is functionally equiavalent to $number = null, which is faster (granted the difference is neglible but the principle stands).

Overall, though, a useful primer for beginners.

Dajve

Elias

September 21st, 2010

@Thomas Tourlourat @Thibaut Allender I didn’t include it on purpose. I’ve got plans to introduce it later though. Teaching stuff which might seem unusefull to the reader can be taught way better with real life examples included.

@gundisalvus @JT Snap! Silly mistake. Thanks for clearing things up.

@Dajve Working with references is also something which requires real life examples to make the user aware of its use.

Your ‘it is just null’ statement makes sense, but what about undeclared variables, they are null too? They’re even identical according to ===.

See the ‘Data Type Switching’ where the user is warned for the expensivity of type switching. I could and probably should have included your point though.

Ankur

September 21st, 2010

thanks JT, i was wondering how PHP would know if 0111001 isnt just 111,001 in decimal because the convention of starting with a 0 for octal wasn’t familiar to me.

Mittal Patel

September 22nd, 2010

Very nice article for beginners !
Though I knew almost everything of it already but enjoyed reading this. :-)

Dajve

September 24th, 2010

@Elias

> @Dajve Working with references is also something which requires real life examples to make the user aware of its use.

I understand that working with references is not something to go into in this guide, it was just to illustrate the fact that there is a real difference between a variable being unset and being set to null. My point is simply that stating
“// The $new_items variable doesn’t exist now
$new_items = null;”
and
“unset() is a PHP function that is the same as doing $player_name = null;”
is inaccurate and misleading, especially for a beginner who may be encountering this for the first time.

> Your ‘it is just null’ statement makes sense, but what about undeclared variables, they are null too? They’re even identical according to ===.
Undeclared variables aren’t null but they do evaluate to null, hence the results are identical; the fact that PHP will trigger an “undefined variable” notice shows that there is a problem with the statement. Also, the existence of both is_null() and isset() functions shows the two types should be dealt with discretely.

Teaching a beginner that this is a valid method of working with variables is, in my opinion, somewhat irresponsible. For example, a developer who disregards the undefined variable notice because he’s grown accustomed to it appearing when working with null values is going to have a much harder time troubleshooting should he make a typo in a variable name becuase he’s already disregarding that message.

As I say, I do think this is a useful primer for beginners, but there is an important distinction between something which exists and something which is null. For an article geared towards this level of developer, it’s enough to make the reader aware of this fact without going into details; the problem I had is that you explicitly state the opposite on two occasions.

To give a real world example, it’s the difference between having an empty cup and not having a cup at all. Most of the time you’re concerned with the contents of the cup, which evaluate to the same thing (neither the empty nor non-existent cup contain anything). In the future, though, believing that there is no difference between the non-existant (unset) and empty (null) cups because that’s what you were taught can lead to a horrible mess when you try to pour water into something that isn’t there.
OK, so that’s a slightly silly analogy but my point stands: despite the fact that, in most situations, you’re more concerned by the fact you have no coffee rather than whether there is a cup there or not, there is still a difference between the two states.

> See the ‘Data Type Switching’ where the user is warned for the expensivity of type switching. I could and probably should have included your point though.

Re: the difference between (unset)$foo and unset($foo)? That was more an incidental point about the quirkiness of PHP – to be honest, I can’t understand the inclusion of an (unset) typecast, especially one that works differently to the unset() function, so I never use it. But that’s a separate discussion – just thought it was the kind of point that belonged in the comments for those of us who read this far =o)

Anyway, that turned out longer than I expected! Don’t think I’m having a pop at what is a good article overall, I was just burned by incorrect statements of fact when I was starting out and know the difficulties trying to troubleshoot with false assumptions.

Dajve

achmatim

September 29th, 2010

Sir, how about string literal with single quote (‘) and double quote (“). Is it different..? Some people says that single quote is more faster than double quote.

Kushal

October 19th, 2010

Good article… this is first time i heared about var_dump()..
Expecting more article like this…

Neil H

November 14th, 2010

This is a great tutorial. For the record, I also really appreciate Dajve’s clarity in explaining the difference between unset() and $somevar = null;

While it will be some time before the distinction carries much weight with my studies, .01% worth of ambiguity now could turn into a substantial habitual error for me later on.

Thanks Elias (and Dajve).

vistor030897u

February 27th, 2011

well explained and thanks much (excuse my english) ^_^

shadows

April 5th, 2011

good articel :D

Shoffy

May 2nd, 2011

I’m trying to do this and the $$ trick doesn’t seem to be doing it.

$_SESSION['ip'] = ’127.0.0.1′;
$var = ‘ip’;

echo $_SESSION[$$var]; // echoes nothing
echo $_SESSION['ip']; // echoes 127.0.0.1

help?

issam

May 30th, 2011

im new to php and i have to say that its a very ugly language …. compare it to c#, java or even C its an ugly language … the main reason for this is that every variable must start with $, it just make the code ugly and hard to follow and read … i wonder if there a solution to this $ problem

Leave a Comment

Subscribe to the comments on this article.