PHP Tutorial – Variables

One of the fundamental components of most every programming language is the variable. A variable is a named storage location in memory in which you can store some data. During the execution of the program, the variable’s value can be saved, retrieved, and manipulated in various ways that depend on the type of data stored in the variable. For example, numeric data can be added, subtracted, multiplied, and so forth, while textual data can be searched, split apart, and concatenated with other data.

In this article we’ll look at the rules for naming variables, how to assign them values, and manipulate the values in various ways. We’ll also take a look at two facilities in PHP for referring to a variable’s value through another variable.

Variable Names

Variable names in PHP are prefixed with a dollar sign ($). After the $, the first character can be a letter or an underscore. Subsequent characters can be letters, numbers, and underscores. There is no fixed limit on the length of a variable name and case is significant. For example, $ClosePrice and $closePrice are two different variables. Here are some examples of legal variable names:

$openPrice
$OpenPrice
$open_price
$_open_price
$OPEN_PRICE

All of these examples begin with a $, followed by a letter or underscore. Subsequent characters are letters, numbers, and underscores. While you are permitted to use a mixture of uppercase and lowercase letters, keep in mind that variable names differing only in case are different variables. For instance, the first two variables in the list above would be considered different variables.

Note: In addition to the characters a through z and A through Z, the specification for letters in variable names includes symbols in the range of 127 through 255. This range includes symbols such as €, ˜, ™, ¢, ©, ®, ß, ñ, and ü. However, the entry and display of such symbols may be problematic in some editors, browsers, and terminal emulators.

Some illegal variable names include:

$$tring
$30_day_average
$open-price

The variable name on line 1 is illegal because the first character after the initial $ is another $. The variable on line 2 is illegal because the first character after the $ is a number. The variable on line 3 is illegal because it contains a hyphen.

A popular convention for naming variables is a style called lower camel case. This convention uses a lowercase letter as the first character of a variable name. The remaining characters are lowercase letters with uppercase letters used at the beginning of words within the name. Examples of this usage include: $symbol, $instrumentName, $openPrice, and $dailyPriceRange.

Variables in PHP can be assigned when they are first referenced, but this isn’t a requirement. For example, both of the following declarations are legal.

$openPrice = 35.14;
$closePrice;

The first statement declares a variable named $openPrice and assigns it the value 35.14. The second statement declares a variable named $closePrice without initializing it. It will have the value NULL until it is assigned. However, it is good practice to always initialize variables when they are declared because the actual value of an uninitialized variable in an expression will depend on the context in which it is used. If used as Boolean, an uninitialized variable will be considered false; if used an integer, it will be 0; if used as a float, it will be 0.0; and if used as a string it will evaluate to the null string.

The assignment operator is the equal sign (=). It takes the value of an expression on the right side and stores it into the variable named on the left side. Recall from the last article that the semicolon at the end of each line is required. It tells the PHP interpreter that the end of the statement has been reached and it should now be executed.

Let’s take a look at some assignments in the PHP script below.

<?php
$openPrice = 35.14;
$closePrice = 36.12;
$dailyRange = $closePrice - $openPrice;

echo "\$openPrice  = ", $openPrice,  "\n";
echo "\$closePrice = ", $closePrice, "\n";
echo "\$dailyRange = ", $dailyRange, "\n";
?>

Notice that the first and last lines of the script contain the <?php and ?> tags and that there is no HTML in the file. The statement on line 2 creates a new variable called $openPrice and initializes it with the value 35.14. The statement on line 3 creates a variable called $closePrice and initializes it with the value 36.12. Both $openPrice and $closePrice are floating point variables because they are initialized with floating point (decimal) values.

The statement on line 4 creates another floating point variable called $dailyRange and assigns it the value of an expression. We learned in the last article that an expression is some combination of variables, values, and operators that, when evaluated, results in a value. In this example the expression $closePrice – $openPrice results in the value that represents the difference of the values of the two variables. The result of the expression is then assigned to the $dailyRange variable. Since the expression’s value (0.98) is also a floating point number, $dailyRange is a floating point variable as well.

0025-10The variables in the script can be visualized by the simplified diagram on the right. $openPrice, $closePrice, and $dailyRange refer to locations in memory, each of which holds a floating point number.

The echo statements on lines 6-8 display the variable names and their values. We saw the echo statement in the last article where we displayed the message Hello, world! in the IDE’s Output pane and in a web browser. These echo statements display the variable name followed by an “=” sign, the value of the variable, and a newline (\n) character. Notice the backslash (\) before each $ in the strings. This \ escapes the $ so that PHP will actually print it and the variable name instead of substituting the value of the variable. We’ll see another way to do this in the next article. The newline character causes a carriage return in the output so that each message appears on a line by itself.

The script above produces the following output.

$openPrice  = 35.14
$closePrice = 36.12
$dailyRange = 0.98

Variables can also store other types of data. In the example below we see variables holding an integer, a string, and a Boolean value. We’ll examine all of the PHP data types in more detail in the next article.

<?php
$days = 5;          // integer
$symbol = "AAPL";   // string
$uptrend = TRUE;    // Boolean
?>

Variable Variables

PHP allows a variable to contain the name of another variable. Consider the example below.

<?php
$openPrice = 35.14;
$closePrice = 36.12;
$highestPrice = "closePrice";

echo "\$openPrice    = ", $openPrice,  "\n";
echo "\$closePrice   = ", $closePrice, "\n";
echo "\$highestPrice = ", $highestPrice, "\n";
?>

0025-11On lines 2 and 3 we create two floating point variables and assign them values as before. On line 4 we create a string variable called $highestPrice and assign it the value “closePrice”. Notice that this string just contains the name of the closePrice variable and not the $ prefix character. On lines 6-8 we print the variables and their values. The output is shown below.

$openPrice    = 35.14
$closePrice   = 36.12
$highestPrice = closePrice

Note that the actual value of the $highestPrice variable is the string value “closePrice”. By placing an additonal $ in front of $highestPrice, i.e. $$highestPrice, we can get the value of the variable whose name is stored in the $highestPrice variable. Take a look at the revised example below where we added the highlighted line.

<?php
$openPrice = 35.14;
$closePrice = 36.12;
$highestPrice = "closePrice";

echo "\$openPrice     = ", $openPrice,  "\n";
echo "\$closePrice    = ", $closePrice, "\n";
echo "\$highestPrice  = ", $highestPrice, "\n";
echo "\$\$highestPrice = ", $$highestPrice, "\n";
?>

0025-12Here, we’ve added a new echo statement on line 9 to print the value of the expression $$highestPrice. When PHP sees the expression $$highestPrice it expects to find the name of a variable stored in $highestPrice. It then uses this name as a variable in which to find the final value of the expression to be printed as shown below.

$openPrice     = 35.14
$closePrice    = 36.12
$highestPrice  = closePrice
$$highestPrice = 36.12

Since the value of a variable variable is just a string, it can be assigned different values as the program runs. We can demonstrate this by adding the highlighted code below to the previous example:

<?php
$openPrice = 35.14;
$closePrice = 36.12;
$highestPrice = "closePrice";

echo "\$openPrice     = ", $openPrice,  "\n";
echo "\$closePrice    = ", $closePrice, "\n";
echo "\$highestPrice  = ", $highestPrice, "\n";
echo "\$\$highestPrice = ", $$highestPrice, "\n\n";

$highestPrice = "openPrice";

echo "\$openPrice     = ", $openPrice,  "\n";
echo "\$closePrice    = ", $closePrice, "\n";
echo "\$highestPrice  = ", $highestPrice, "\n";
echo "\$\$highestPrice = ", $$highestPrice, "\n\n";
?>

0025-13
The additional code reassignes the $highestPrice variable to the string “openPrice”. The first echo of $$highestPrice prints the value of $closePrice and the second echo of $$highestPrice prints the value of $openPrice.

$openPrice     = 35.14
$closePrice    = 36.12
$highestPrice  = closePrice
$$highestPrice = 36.12

$openPrice     = 35.14
$closePrice    = 36.12
$highestPrice  = openPrice
$$highestPrice = 35.14

0025-14You can also use this mechanism to dynamically create new variables. For example, the code fragment below creates a variable called $a that holds the value b, a variable $b that holds the value c, and so on. This pattern can be extended indefinitely using additional dollar-signs for each new level of indirection as shown in the script below.

<?php
$a = "b";
$$a = "c";
$$$a = "d";
$$$$a = "e";
$$$$$a = "f";
echo $a, $b, $c, $d, $e;
?>

This script will produce the output:

bcdef

The important point to keep in mind about variable variables is that the variable name is just a string that is constructed at runtime and there is no physical connection between it and the variable to which it refers. Thus, if an incorrect name is assigned to the variable variable, you will get an error message when it is referenced. As an example, the code below incorrectly assigns the string “ClosePrice” instead of “closePrice” to $highestPrice on line 4.

<?php
$openPrice = 35.14;
$closePrice = 36.12;
$highestPrice = "ClosePrice";

echo "\$openPrice     = ", $openPrice,  "\n";
echo "\$closePrice    = ", $closePrice, "\n";
echo "\$highestPrice  = ", $highestPrice, "\n";
echo "\$\$highestPrice = ", $$highestPrice, "\n";
?>

When the program tries to find the variable $ClosePrice it generates an error as shown below (recall that case is significant in variable names so $ClosePrice is not the same variable as $closePrice).

$openPrice     = 35.14
$closePrice    = 36.12
$highestPrice  = ClosePrice
$$highestPrice = PHP Notice:  Undefined variable: ClosePrice in /home/charlie/NetBeansProjects/PhpTutorial/test.php on line 9

References

A reference is a variable whose value points to another variable. This allows you to refer to a storage location with multiple names.

To demonstrate references let’s begin with some normal variables. Consider the code fragment below. We create and initialize two floating point variables $openPrice and $closePrice. These variables refer to two different values stored in two different locations in memory. We then create a third variable, $highestPrice, and assign it the value of $closePrice.

$openPrice = 35.14;
$closePrice = 36.12;
$highestPrice = $closePrice;

0025-20As illustrated in the diagram to the right, $highestPrice has its own memory location and a value that is a copy of the value stored in $closePrice. After the assignment, $closePrice and $highestPrice can each be changed and referenced independently. This can be seen in the example below. After the variables are created and initialized, the $highestPrice variable is altered on line 10.

<?php
$openPrice = 35.14;
$closePrice = 36.12;
$highestPrice = $closePrice;

echo "\$openPrice    = ", $openPrice,  "\n";
echo "\$closePrice   = ", $closePrice, "\n";
echo "\$highestPrice = ", $highestPrice, "\n\n";

$highestPrice = 37.02;

echo "\$openPrice    = ", $openPrice,  "\n";
echo "\$closePrice   = ", $closePrice, "\n";
echo "\$highestPrice = ", $highestPrice, "\n\n";
?>

0025-21This change only affects the value of $highestPrice and not the value of the $closePrice variable as can be seen by the echo output before and after the change.

$openPrice    = 35.14
$closePrice   = 36.12
$highestPrice = 36.12

$openPrice    = 35.14
$closePrice   = 36.12
$highestPrice = 37.02

0025-22Let’s now look at slightly different example. The only change made in this version is on line 4. Here we assign to $highestPrice, not a copy of $closePrice as we did in the last example, but a reference to $closePrice. This reference makes the $closePrice and $highestPrice variables refer to the same location in memory, and thus, the same value. Note the use of the reference assignment operator (=&) before the $closePrice variable name.

<?php
$openPrice = 35.14;
$closePrice = 36.12;
$highestPrice =& $closePrice;

echo "\$openPrice    = ", $openPrice,  "\n";
echo "\$closePrice   = ", $closePrice, "\n";
echo "\$highestPrice = ", $highestPrice, "\n\n";

$highestPrice = 37.02;

echo "\$openPrice    = ", $openPrice,  "\n";
echo "\$closePrice   = ", $closePrice, "\n";
echo "\$highestPrice = ", $highestPrice, "\n\n";
?>

0025-23As the output below demonstrates, changing the value of the $highestPrice variable also changes the value of $closePrice. Similarly, changing the common value using the $closePrice variable would be seen in $highestPrice as well.

$openPrice    = 35.14
$closePrice   = 36.12
$highestPrice = 36.12

$openPrice    = 35.14
$closePrice   = 37.02
$highestPrice = 37.02

0025-24A reference variable can refer to different variables at different times during the program’s execution. We can demonstrate this by adding the highlighted code below to the previous example. During the program’s execution the $highestPrice reference variable is altered so that it points to $openPrice instead of $closePrice on line 16. The common value is changed and printed to show that it now points to $openPrice.

<?php
$openPrice = 35.14;
$closePrice = 36.12;
$highestPrice =& $closePrice;

echo "\$openPrice    = ", $openPrice,  "\n";
echo "\$closePrice   = ", $closePrice, "\n";
echo "\$highestPrice = ", $highestPrice, "\n\n";

$highestPrice = 37.02;

echo "\$openPrice    = ", $openPrice,  "\n";
echo "\$closePrice   = ", $closePrice, "\n";
echo "\$highestPrice = ", $highestPrice, "\n\n";

$highestPrice =& $openPrice;
$highestPrice = 38.12;

echo "\$openPrice    = ", $openPrice,  "\n";
echo "\$closePrice   = ", $closePrice, "\n";
echo "\$highestPrice = ", $highestPrice, "\n\n";
?>

As the output below shows the values of both $closePrice and $openPrice are changed using the $highestPrice reference at different points during the program’s execution.

$openPrice    = 35.14
$closePrice   = 36.12
$highestPrice = 36.12

$openPrice    = 35.14
$closePrice   = 37.02
$highestPrice = 37.02

$openPrice    = 38.12
$closePrice   = 37.02
$highestPrice = 38.12

Let’s take a look at one more example. In the code below we accidentally create a reference to the non-existent variable $ClosePrice instead of $closePrice. Recall that an analogous mistake with variable variables in the last section caused PHP to generate an error when the variable was referenced.

<?php
$openPrice = 35.14;
$closePrice = 36.12;
$highestPrice =& $ClosePrice;

echo "\$openPrice     = ", $openPrice,  "\n";
echo "\$closePrice    = ", $closePrice, "\n";
echo "\$highestPrice  = ", $highestPrice, "\n\n";
?>

In the output below, we see that no error was generated but the value of the reference is NULL. It turns out that when you use the =& operator with a variable that does not exist, PHP will create it for you. Thus, in the example above, PHP creates a new variable called $ClosePrice and assigns a reference to it to $highestPrice.

$openPrice     = 35.14
$closePrice    = 36.12
$highestPrice  = 

We can verify this with the script below. In this version we add the highlighted code to assign a value via the reference $highestPrice and then echo the values of both $closePrice and $ClosePrice.

<?php
$openPrice = 35.14;
$closePrice = 36.12;
$highestPrice =& $ClosePrice;

echo "\$openPrice     = ", $openPrice,  "\n";
echo "\$closePrice    = ", $closePrice, "\n";
echo "\$highestPrice  = ", $highestPrice, "\n\n";

$highestPrice = 37.02;
echo "\$closePrice    = ", $closePrice, "\n";
echo "\$ClosePrice    = ", $ClosePrice, "\n";
?>

0025-25In the output below we can see that a new variable $ClosePrice is now available and has the assigned value 37.02 while the $closePrice variable retains its original value of 36.12.

$openPrice     = 35.14
$closePrice    = 36.12
$highestPrice  = 

$closePrice    = 36.12
$ClosePrice    = 37.02

References are mainly used in function calls and returns. We’ll have much more to say about references when we discuss functions in a later article.

In this article we discussed PHP variable declaration and initialization, naming rules and conventions, and using variables in expressions and statements. We also looked at two methods of referencing one variable from another: variable variables and references. I only mentioned data types in passing, but in the next article we’ll examine all of the PHP data types in more detail.

Speak Your Mind

*