Skip to main content ↓
PHP logo with an oval gradient background over a pattern of binary code in shades of blue.

PHP Variables: The Ultimate Guide

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.

// 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.

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.

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.

// Valid
// Valid
// Valid
// Not valid - has a space
$player name;
// Not valid - starts with a number
// Valid

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.

12 03 parse errorPHP 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:

$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.

$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:

$player_name = 'Freddy';
// Prints out "Hello Freddy!"
echo 'Hello ' . $player_name . '!';

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

$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.

$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.

// A variable without any value assigned to it, equals null
// 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;

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.

$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.


$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 (,).

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’.

12 04 var dumpJust 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.

$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:

echo '<pre>';
$number = 10;
echo '<br />';
// Divide 10 by 6.
$number /= 6;
echo '</pre>';

12 05 int to floatOur 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.

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.

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); ?>


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

Make estimating web design costs easy

Website design costs can be tricky to nail down. Get an instant estimate for a custom web design with our free website design cost calculator!

Try Our Free Web Design Cost Calculator
Project Quote Calculator