Updated November 15, 2009 at 6:28 pm
The concept of a variable is not too difficult to understand, and if you have any experience with basic algebra or advanced mathematics, you have already been introduced to variables. They work very much the same way in computer programming. A variable can be thought of as any entity that has the ability to take on different values.
Two terms you will often hear in relation to technology are
static and
dynamic. Static is anything that doesn't change. As with most rules, there are exceptions, but you can normally think of static as being something that stays consistent, either unto itself or across a population. Dynamic is anything that is likely to change, usually based on a given condition. All of your PHP code will be static, and variables, while normally dynamic, can be static in some cases.
Without variables, PHP would have very little use. Back in the 1990s, during the early days of the modern internet, most websites were static. Information had to be manually updated by the web master. This involved editing the HTML or text files that made up a web page and linking them together. It was very difficult to make massive changes to the layout or structure of your website. While tools such as SSI, or server-side includes, made some modification possible, most pages were very static and not updated as frequently as many sites are today.
Variables make it possible to include content on your website that has the ability to change without the web master having to make constant changes behind the scenes. Examples where variables can really come in handy include the ability to offer user accounts, which lets you customize content based on the person browsing the site, and the ability to develop templates that all pages of the site can use to display content in a uniform fashion.
Defining Variables
As with all PHP code, your variable definitions will exist between opening and closing tags. In most cases the variable definition will end in a semicolon. Each variable has a name, and names can consist of letters, numbers, and the underscore ( _ ). Each variable may only start with a letter or underscore, and all variables are case-sensitive. In PHP, a variable is almost always identified by the US dollar sign, or $, which appears immediately before the variable name.
You will want to name your variables carefully. It's always a good idea to keep your naming scheme uniform throughout your code, and you should always use names that identify the value contained within the variable. For example, if you were programming a virtual car and you wanted to assign each wheel its own variable, which could be used to store information such as tire pressure, it would be better to name your variables $rightFrontWheel, $leftFrontWheel, $leftRearWheel, and $rightRearWheel than a non-uniform $RIGHTFRONTWHEEL, $left_front_wheel, $leftRearWHEEL, and $right_REARwheel. Not only is it easier to read your code when your naming is consistent, but it's also easier to remember variable names if you don't have a list of variables in front of you.
Assigning a variable is easy, and the definition follows the general syntax of __variable__ = __value__; Here is some PHP code that you can run that would define several variables:
<?php
$myHeight = 70;
$bobsHeight = 72;
$marksHeight = 65.5;
?>
Before we dig too deep into variables, I would like to address the concept of variable types. When you are programming in most languages, you will be required to explicitly define the type of information the variable can store. Sample types include integers, which are simply whole numbers, doubles, which are fractional numbers, and Booleans, which are values that are either true or false. While variable types are certainly important to both programming and PHP, they are not essential at this point of the series, and we will cover them at a later time.
Basic Math
You can perform basic calculations on variables much like you would on an advanced calculator. Permissible symbols include
+ for addition,
- for subtraction,
* for multiplication,
/ for division, and
% for modulus calculations. Grouping is also allowed by using parentheses. Here are some basic examples:
<?php
$three = 1 + 2;
$seven = (2 * 3) + 1;
$two = 10 % 8;
$fifteen = (5 / 2) * (6-1) + 2.5 - 0;
?>
Strings as Variables
While it's great that you can save numbers into variables, what about regular text like in our Hello World example? PHP makes it very easy to save this type of text, which is often referred to as a string. The name "string" is derived from the idea of stringing characters and symbols together to form words and sentences. Before we give our first example, we need to identify the two types of strings available.
When defining a variable, you mark off the string by placing it within quotation marks. While that sounds easy enough, you need to understand the importance of choosing either single quotes ( ' ) or double quotes ( " ). A variable marked off by single quotes is referred to as a verbatim string literal. What this means is that PHP will not analyze the contents of the string; rather, PHP will store the string contents so that the printed string will appear on the screen just as it appears in your code, regardless of its contents. Here's how you could store my name as a verbatim string:
<?php $myName = 'Chris'; ?>
If a string is marked off with double quotes, the contents of the string will be analyzed by PHP. Any PHP variables contained within the string will be replaced by the value of the variable. For example, if we wanted to store a Hello greeting that also included a name, we could use the following code:
<?php
$name = 'Chris';
$greeting = "Hello, $name.";
?>
Nothing will happen if you run this example since we're not printing anything out to the screen. If you were to print out the value of the greeting, as you will see how to do momentarily, the message would read
Hello, Chris.
Significance of Variable Order
It is worth pointing out that PHP code can be written in one of three ways. Most of our early examples will be in what is known as procedural programming. We will introduce the other two types of programming later. In procedural programming, the PHP interpreter starts at the beginning of the file and works its way through the code, line by line, or procedure by procedure. This is important to understand since you can only use a variable after you have defined its value, and the variable's value at any given time depends on its position within the procedures.
Variables have the ability to change, so it is possible for one variable to hold many different values throughout the duration of a program's existence. Taking the above example, if you were to define the $name variable after the greeting, then the greeting would simply be "Hello, ." That's probably not what you want, so you need to be careful.
Printing Variables
As we saw in Hello World, you can use the "echo" statement to print out a string, but you can also use it to print out a variable. Let's write a very short program that prints out a name and a US currency value. In this mini program, the name will be a variable, but the amount of money will be static. When should we use single quotes and when should we use double quotes? Here's the code:
<?php
$name = 'Chris';
echo "Greetings, $name. ";
echo 'You have $50.00.';
?>
A few things are going on in this example. First, we define a variable "name" to be equal to my name. Since my name is static in this example, we can use single quotes. It is permissible to use double quotes around the name, but it's not necessary by any means. Our second line echoes out a string, just like in Hello World, but you will also notice a variable included directly within the string. Double quotes are required for this line so that PHP knows to analyze the contents. Had we used single quotes, the output would be "Greetings, $name. " That's not what we want. We want PHP to replace any variables in the string with the values of those variables. If you save the above code in a PHP file and view it on your web server, the output should read: "Greetings, Chris. You have $50.00."
As a side note, if you replace the single quotes on the last line with double quotes, the output will look the same. This is due to the fact that the first character after the dollar sign is a number. PHP knows that this cannot be a variable since variables cannot start with numbers. Had the 5 been any letter or an underscore, the $ would have been treated as the start of a variable which had no value, and the output would have read: "Greetings, Chris. You have .00."
What do you do if you want to combine literal dollar signs and variables? One option is to break up your echo lines into multiple statements. We'll look at the two other options below.
Escaping Characters
Sometimes you will want to use variables or strings in ways that may confuse the PHP interpreter, or in the case of a database, the MySQL query engine. A great example of the former would be printing out sample PHP code. The following code would not work as intended:
<?php
$varValue = 'apples are red';
echo "Here's a PHP variable definition: $varName = '$varValue';";
?>
If you run this code, the output would read: "Here's a PHP variable definition: = 'apples are red';." How can you easily force the dollar sign to be treated literally, so the code will make more sense? You must escape the dollar sign character.
Escaping characters is as simple as adding a backslash ( \ ) immediately before the character. Here's a corrected form of the code above:
<?php
$varValue = 'apples are red';
echo "Here's a PHP variable definition: \$varName = '$varValue';";
?>
This example will print out the text "$varName," but the $varValue will be replaced with the value of the variable since the dollar sign in $varValue is not escaped.
This can get a little tricky if you change your quotes between double and single quote marks. For example, if you have escaped characters within double quotes and you switch to single, the backslash will be treated literally instead of as an escape character, and it will appear in your output, probably not as intended. If you want to print out a literal backslash in a regular string and the backslash immediately precedes an escapable character, you simply escape the backslash.
Here's an example where the backslash will appear since it is escaped, but neither the variable name nor its value will appear at all since its value hasn't been set and the dollar sign isn't escaped:
<?php
echo "Here's a backslash: \\$variable";
?>
If you wanted to escape both the backslash and the dollar sign above, you would end up having three backslashes in a row. There is also an exception to a backslash being treated literally within verbatim strings. We will cover that exception shortly.
Variable Concatenation
What do you do if you want to combine several strings or variables into one? This can be accomplished through string concatenation in two ways. You can either set a variable inline using the period ( . ) or by adding new syntax to the possible variable definitions. The first example shows how you can add two strings together using period concatenation:
<?php
$world = 'World';
echo "Hello" . ' ' . $world;
?>
In this example, we are concatenating three strings. The first string is the word "Hello." The second string is a blank space. In this case it's a verbatim string, but it can also be a regular string. The third string is a variable, which was defined as a verbatim string that includes the word "World." Now let's view a second option. We will set a variable in three parts, and then echo out the result.
<?php
$var = 'Hello';
$var .= ' ';
$var .= 'World';
echo $var;
?>
In this example we are concatenating two different verbatim strings onto the end of a pre-existing variable, which was first defined to equal the word "Hello." Be extra careful with this type of concatenation. If you are relying on the variable being empty, it's always a good idea to reset a variable instead of concatenating onto a possibly pre-existing variable. You can reset a variable by redefining it. For example, the following code would echo "Bob."
<?php
$name = 'Chris';
$name = "Bob";
echo $name;
?>
If you didn't want the variable $name to have a value, set it equal to "", which is referred to as the empty string.
Quote Mark Exceptions
Whenever you are using quote marks, you need to remain consistent for a given string. If you open a string with a single quote, you must close that string with a single quote. If you open a string with a double quote, you must close the string with a double quote. You are, however, allowed to concatenate both regular and verbatim strings.
Whenever you are using quotation marks, you don't have to worry about escaping anything as long as the would-be-escaped quote mark is the opposite type of quotation used to designate the string. You do not have to escape single quotes if the string is regular, and you do not have to escape double quotes if the string is uses single quotes.
A basic quote conflict arises when you want to use a single quote within a verbatim string or when you want to use a double quote within a regular string. Here's the backslash exception we mentioned earlier. In almost all cases, including a backslash within single quotes will result in that backslash being treated literally. After all, whenever you use single quotes, the string will be treated exactly as it appears. But can you escape a single quote, say, used as an apostrophe, if it's within a verbatim string? Yes. If you need to include a single quote within a verbatim string, you are allowed to escape it and the backslash will not appear. Escaping a double quote mark within a regular string is accomplished by adding a backslash immediately before the double quote mark, just as you would for any other escaped character.
Review
A lot of information has been presented in this tutorial. It is not worth your time to try and remember all of these rules now. You will discover most of the possible error cases on your own, and I will try to point some out as we progress deeper into the language. The main goal is to introduce you to the existence of these many rules, so you won't be completely surprised later down the road.
Let's quickly review all of the main concepts found in this tutorial. We will write a very short program that prints out PHP examples. I suggest you run this code to see the output. Simply create a PHP file in either your helloworld folder or in your document root, navigate to the file in your browser, and the output should appear on your screen.
<?php
$one = 1;
$two = 2;
echo "\$one = $one; \$two = $two; ";
echo "This new variable will hold a value of ";
echo $one + $two;
echo '. $three = $one + ' . "\$two;";
?>
The first two lines create our variables, one and two, and assign the values 1 and 2 into the variables. The third line prints out the variable names and the values held in those variables. Note how we escape the dollar sign so the variable name is printed instead of its value. The fourth line prints out a message.
In this example the line is a regular string, but it could also be treated literally. The fifth line prints out the value of $one + $two. If you were to change the values of $one, $two, or both, this echo statement would print out the new value. You wouldn't want it to read "This new variable will hold a value of 3." if $one was equal to 4 and $two was equal to 1. That wouldn't make any sense.
The final echo line is two strings concatenated together. The first string is a verbatim string that includes the $three and $one variables. Since we want these names printed to the screen, we either need to put the full name in a verbatim string, as we have done, or we need to escape the dollar sign. We could have put the contents of the second string, the $two, in with the first verbatim string and everything would have worked out. The method I chose concatenates the first verbatim string with the second, regular string. Since we want the $two variable name to be printed literally, we must escape the $. Had I not escaped the dollar sign, the output would have read "This new variable will hold a value of 3. $three = $one + 2;" This is perfectly valid code, and in some programs you may not care either way, but our intent was to print out the variable name and not the value.
In our next tutorial, we will look at a continuation of variables, string manipulation, and additional PHP syntax.