# Variables In PHP (part 1) Variables are probably one of the most commonly used code constructs you’ll come across while programming. If you have any experience of mathematics, especially algebra, you’ll be aware of the concept of using symbols to represent unknown quantities in equations, like in the following example

``````x + 5 = 7;
from this we can deduce that x = 2
``````

In PHP it works in a similar fashion, except we usually know the value of x, and simply assign it a specific value, such as x = 5. We can then use that value to perform calculations using other symbols and numbers. For example

``````\$x = 5  //x now equals 5
\$y = \$x + 10  /* y now equals 5 + 10 */
``````

These symbols in PHP are known as variables and require you to follow a specific syntax to use them properly. Once you understand the principles behind them, you’ll begin to see how they form a major component of any PHP application, and can be used to store many things other than just numbers. Let us begin though, by guiding you through a few simple examples of the use of variables.

### A simple introduction

A very simple example of the use of a variable in PHP is to hold just one number, e.g.

``````\$x = 5;
``````

All variables in PHP start with a dollar sign, followed by a string of numbers, letters (both lower-case and capitals) and underscores. Variables are also case sensitive, meaning that `\$Variable` is not equal to `\$variable`. The only other requirement of variable naming is that the first character has to be a letter (a-z, uppercase or lowercase) or an underscore. These are examples of valid variable names

``````\$variable_name = 5; //valid - integer
\$VariableName = 25.5; //valid - floating point
\$variable3 = 155; //valid
\$_variable_number_four = "value"; //valid - string
\$_x = "five"; //valid
``````

These are not valid variable names

``````\$1st_variable = 5; //invalid
\$Variable.name = 25; //invalid, cannot have dots in names
``````

Variables are assigned values through the use of the equals sign (`=`) operator. Once a variable has been assigned to a value, that variable symbol can be used in place of the value anywhere in the code. The value of the variable can also be changed at any point during the execution of the code. The same value can also be assigned to multiple variables at the same time, like so

``````\$a = \$b = \$c = 5;
echo "\$a, \$b, \$c";
``````

This produces the output

``````5, 5, 5
``````

### Flexible types

The “type” of a variable is defined by the value you’ve assigned to it. PHP supports a wide range of types, including strings, integers and floats.

``````\$string = "This is a string";
\$integer = 5; //an integer value;
\$float = 4.55; //a "floating point" value
``````

PHP doesn’t explicitly require that you maintain the same type for a certain variable though. If you tried to assign a string value to a variable which previously contained an integer, you’ll encounter no problems. Similarly with any other types, floating point variables can hold integers or strings and so on.

### Strings in PHP

A string in PHP is a variable holding zero or more characters of text, and can be used to store words or sentences to be inserted into the body of a web-page, or to be used in the result of calculations. Strings are specified by wrapping a section of text in single or double quotes. Here are some examples of valid string variables.

``````\$str1 = "This is a string";
\$str2 = 'This also works';
\$str3 = "Splitting strings between lines
is also acceptable";
``````

Here are some considerations to bear in mind when assigning strings

The start and end quotes must be of matching types - you cannot mix single and double quotes. This code is invalid

``````\$str1 = "This code will break';
``````

### Escaping characters

If you’re using single or double quotes within the string itself, this can cause complications. Take the following as an example

``````\$str1 = 'Don't use unescaped quotes'; /* this will break */
``````

Here, the use of the single quote within the string makes PHP think you’re terminating the string after “Don”, and then it expects a semicolon directly after. In this case, the sentence continues and so the code breaks.

A solution to this is to escape the offending character. This is done via the use of the backslash (`\`) character immediately before. Like so

``````\$str1 = 'Don\'t use unescaped quotes'; /* this is now valid code */
``````

This tells PHP to treat the single quote as if it were a character to be printed, rather than an element of the PHP syntax to be processed.

You will also encounter this problem if you try and use the dollar (`\$`) symbol inside strings. Because of the way PHP allows variables to be inserted into strings (and this will be explained further shortly), PHP will interpret any use of the dollar symbol as an attempt to insert a variable. Note that this only happens when using double quotes. For example

``````\$string = "Hello world";
\$str1 = "\$string"; /* will output - Hello world */
\$str2 = "\\$string"; /* will output - \$string */
``````

Escaping characters can be very useful, but if you’re using a large number of quotes and other symbols inside a string, things can get confusing. There is an alternative way to specify strings, Heredoc and Nowdoc syntax, outlined shortly.

### Inserting variables into strings

PHP includes some powerful methods to combine strings with ease, including the ability to quickly join strings together, and the ability to insert other variables into strings.

Variables can be inserted into strings in one of three ways

• Using the dot (.) operator to concatenate strings and variables. Take the following code

``````\$a = "This is ";
\$b = "an example of ";
\$c = \$a.\$b."the dot operator";
echo \$c;
``````

this produces

``````This is an example of the dot operator
``````
• By placing the variable directly into the sentence

``````\$a = "This is ";
\$b = "an example of ";
\$c = "\$a\$b variable/string insertion";
``````

This example will only work when using double quotes or Heredoc syntax, strings defined using single quotes do not possess this functionality.

In this example, we have placed the variable names `\$a` and `\$b` directly into the string. This is a quick and easy way of printing variable names into strings, but you must bear in mind…

You must make sure to have a space after a variable name and any following text For more complex variables such as arrays (outlined later), their more complex syntax requires that you surround them in braces e.g.

``````\$array = array();
\$array["var"] = "This is an array ";
\$string = "{\$array["var"]} inserted into a string";
echo \$string;
``````

Giving us

``````This is an array inserted into a string
``````
• When using the `echo` statement only, variables can be joined together by placing commas between them. This is actually a slightly faster way of printing multiple variables than with the dot operator, but the difference is negligible except for when performing millions of these operations

``````\$a = "An example of ";
\$b = "joining variables ";
echo \$a,\$b,"together with commas";
``````

Giving us

``````An example of joining variables together with commas
``````

Note that the following code is invalid, since this method only works with `echo`

``````\$a = "An example of ";
\$b = "joining variables ";
print_r (\$a,\$b,"together with commas"); //invalid
\$c = \$a,\$b,"together with commas"; //invalid
``````

### Heredoc syntax for strings

Heredoc syntax is a way to write large sections of text in PHP without the need to worry about escaping quotes. Strings are expressed in this way as follows

• An initial opening delimiter consisting of three “Less than” symbols (`<<<`) and a string of your choice - it doesn’t matter what you choose as long as you follow the naming rules for variables (letters, numbers and underscores. The first character cannot be a number
• On a new line start your string content. This can run onto as many new lines as you like and contain as much content as you require
• When you wish to terminate a new string, on another new line, place your chosen string followed by a semicolon. This must be the only text on the line (not even comments are allowed) and must not be indented

Here is an example

``````\$string = <<<STRINGHERE
This is a Heredoc syntax string.
It's very useful
indeed
STRINGHERE;
echo \$string;
``````

And this produces

``````This is a Heredoc syntax string. It's very useful indeed
``````

Here is an example of a faulty Heredoc string

``````\$string = <<<STRINGHERE
This is a Heredoc syntax string.
It's very useful
indeed. But this one is broken
STRINGHERE; //see the indentation?
//there should be no comment on the previous line either
``````

One useful applicaiton of Heredoc strings is that you can place other variables inside them easily, without the need to wrap them in appropriate quote symbols, or otherwise join them to the other strings.

For example

``````\$a = "10";
\$string = <<<STRING
The value of a is \$a
STRING;
echo \$string;
``````

Gives us

``````The value of a is 10
``````

### Nowdoc syntax for strings

An alternative method to Heredoc is Nowdoc. This is functionally almost identical to Heredoc, but has the distinct difference that no parsing takes place within the string - i.e. no variables are replaced. This is useful if you wish to print content including e.g. PHP variables, without them being evaluated by the interpreter. This is similar to the difference between single (`'`) and double (`"`) quoted strings.

Nowdoc is specified by wrapping the initial opening identifier string in single quotes, as follows

``````\$a = "10";
\$string = <<<'STRING'
The value of a is \$a
STRING;
echo \$string;
``````

Now, the output we recieve is

``````The value of a is \$a
``````

A direct interpetation of the string, with no processing taking place.