Variables, like in algebra are places where you can store numbers. Unlike algebra, in PHP you can store all sorts of data in a variable, including strings (pieces of text), numbers and even lists of numbers or strings (arrays) - you're not just limited to storing numbers in them. This probably doesn't make a lot of sense until you see an example of them being used, so let's look at one:
<?php
$a = 1;
$b = 2;
echo $a+$b;
?>
Variable names in PHP always start with a dollar sign, so here you can see we're using two variables; $a and $b. To create a variable, all you have to do is assign a value to it - in PHP you do not have to declare variables before you use them. First we're assigning the value 1 to $a and the value 2 to $b. Think of $a as being a physical place where we're putting the number 1 and the same thing with $b and the number 2. The final line of code simply tells PHP to output the sum of the two values. If you put this simple program into a file with the .php extension and view it on your web server, you'll see the number 3. Simple right? Let's have a look at a slightly more complicated example:
<?php
$foo = 2;
$bar = 4;
$stool = $foo * $bar; // $stool now contains the value 8
$stool++; // Incrementing $stool - now contains the value 9
echo $stool / 3;
?>
Okay, so we're introducing a number of new concepts here. Firstly you'll see that we're using three variables - $foo, $bar and $stool. You'll also notice that variable names don't have to be one letter long like they do in algebra - you can (and should) use a word to describe what the variable is supposed to contain.
We're using the * operator to multply $foo by $bar, and we're assigning the result of that operation to the variable $stool - on the same line you will see another new concept - a comment; this is a piece of text that is basically ignored by the interpreter. Whenever you see a double forward-slash - // PHP will ignore the rest of the line. This is useful for explaining what your code is doing in the case that it's not immediately obvious.
On the following line you'll see another new operator, the double-plus sign - this adds 1 to the value of the variable (this is called incrementing). You can also use a double-minus sign to take 1 away (decrement).
The final line of code uses the divide operator (forward slash) to divide the value of $stool by 3 and output the result. If you test this program, the output will be the number 3.
To sum all of that up; you can assign values to variables using the equals sign, you can use +, -, /, and * to perform addition, subtraction, division and multiplication respectively. You can use the double-plus or double-minus operators to increment or decrement a variable.
At the beginning of this chapter we mentioned that variables aren't just limited to storing numbers, you can store strings in them as well. Let's have a look at an example of that in practice:
<?php
$text = "Hello world!";
echo $text;
?>
In this very simple example you can see that we're assigning the value "Hello world!" to the variable called $text, and then we're outputting the contents of that variable. As mentioned previously, strings must always be contained within either single or double-quotes. Let's see a more complex example:
<?php
$wibble = "Goodbye";
$wobble = "world";
$wubble = $wibble . " cruel " . $wobble; // concatenation
echo $wubble;
?>
Here you can see an example of string concatenation - this just means joining two strings together. In PHP you do this using the dot operator - in this example we're using the dot operator twice to join three strings together, the first contained in $wibble, the word "cruel" which is never directly assigned to a variable, followed by the string contained in $wobble. When we output the result, we should get the concatenated string "Goodbye cruel world". Notice how you can concatenate both actual strings and variables that contain strings.
Let's have another example:
<?php
$flob = 1;
echo "$flob<br />\n";
echo $flob . "<br />\n";
echo '$flob<br />\n';
?>
This example demonstrates an important difference between single and double quotes - double quotes can contain variables, and PHP will replace the variable name with the contents of the variable. Single quotes however will not do this. Furthermore, the special character sequence \n means "insert a new line here" - this is an actual line break not an HTML <br> tag. If you were to upload this program to your web server, open it in your browser and then select 'View Source' you'd see this as the output:
1<br />
1<br />
$flob<br />\n
Take a minute to understand what's going on here - the first two echo statements are essentially equivalent and produce the same output, but the third echo statement does something slightly different due to the use of single quotes rather than double quotes - rather than outputting the value of $flob, the string '$flob' itself is echoed. Furthermore, \n is being outputted directly rather than being converted into a linebreak. Basically, when you use single quotes - PHP interprets the string as-is without changing it in any way, whereas when you use double-quotes, PHP parses the string for any variable names and various other special character sequences (including \n) and alters the string accordingly.
There's something else more subtle going on here as well - $flob is assigned a number - it's a numerical variable, but rather than using the arithmetic operators on it, we're concatenating it as if it were a string. PHP allows you to do this because it is what we call a loosely-typed language - that means it does know what type a variable is - it knows that $flob contains a number and not a string, but as soon as we use $flob in a string context, it automatically and invisibly converts it into a string. It works the other way around too, let's see an example of that:
<?php
$flim = 6; // $flim is a numerical variable (an integer to be more precise)
$flam = '2'; // $flam is a string containing one character - the number 2
$flooble = $flim * $flam;
echo $flooble;
?>
When we use $flam in a numerical context (ie we apply the multiplication operator to it), PHP automatically does its best to convert the string into a number which can then be multiplied. We end up with $flooble being a numerical variable with the value 12.
Arrays are a special data type that can be used to store multiple items of data. In PHP, all arrays consist of a series of key-value pairs. The key must be either an integer (a whole number) or a string. The value can be any PHP data type including a string, a number or even another array. The key is used to look-up its corresponding value in the array. Again, this probably doesn't really mean a lot until you see it in practice:
<?php
$a[0] = 'Hello';
$a[1] = 'World';
echo $a[0] . ' ' . $a[1];
?>
Here we're creating an array with two elements - the first element we create has the integer 0 as a key and the string 'Hello' as a value. The second element has the integer 1 for a key and the string 'World' as a value. You can see that we refer to elements of an array using square bracket notation - when referring to an element like this it behaves just like a regular variable and we can use the concatenation and arithmetic operators on it just like we did with normal variables above.
There are a number of different ways of assigning values to an array, let's see a couple more examples:
<?php
$aleph = array('Red', 'Green', 'Blue');
$bet[] = 'Antired';
$bet[] = 'Antigreen';
$bet[] = 'Antiblue';
echo $aleph[1] . ' ' . $bet[0];
?>
In both cases here we're creating a numerical array, but we're allowing PHP to choose the keys for us. You can use the array() syntax as we're doing here with $aleph to create an array with many values in a single succinct line of code. PHP will automatically choose the keys starting at 0 and adding 1 for each element - to here $aleph is an array of 3 elements with the highest numbered key being 2. Notice that $aleph refers to the entire array and $aleph[0] refers to the element with the numerical key 0.
In the case of $bet, we're using empty square brackets to add an element to the end of a numeric array. When you use empty square brackets, PHP always takes the highest existing key in the array, adds one to it and uses that as the new key. In the case of a new array, PHP always uses 0 as the first key.
Let's have one final example of numerical arrays before we move on:
<?php
$primes = array(2, 3, 5);
$primes[] = 7;
$primes[] = 11;
var_dump($primes);
?>
In this example you can see that it's possible to create an array using array() and then add elements to it using empty square bracket notation. We've also introduced something entirely new - the var_dump() function. We'll discuss functions in a lot more detail in a later chapter, but for now let's just focus on what var_dump() actually does. var_dump() is used to show you the contents of a variable in an easily readable form - this is particularly useful in the case of arrays because it will give you an output like this:
array(5) {
[0]=>
int(2)
[1]=>
int(3)
[2]=>
int(5)
[3]=>
int(7)
[4]=>
int(11)
}
The first line tells us that we have an array with 5 elements, and it then goes on to list the keys and values for each of those elements. Notice that the highest numbered key is 4, but we have 5 elements in total. This is because we start counting array indices at 0 rather than one. You should also notice that var_dump tells us the type of each variable as well as its value - we see easily see from this var dump output that $primes is of type array and each of its elements is of type int (meaning integer).
When we introduced arrays we stated that the key can either be an integer or a string. In some programming languages, this is called a hash map or an associative array, however, PHP does not make this distinction and all arrays in PHP are essentially the same. Lets see an example of an array with string keys:
<?php
$bazola = array('foo' => 'bar',
'toto' => 'titi',
'pippo' => 'pluto');
$bazola['aap']='noot';
var_dump($bazola);
?>
There's a few new concepts here - the most obvious is the fact that we're now assigning $bazola in a multi-line statement. Nobody ever said a single statement could only ever occupy one line; you can insert line breaks whenever you think it will make the code easier to read. PHP looks for the statement terminator (semi-colon) in order to indicate the end of the statement - it doesn't care about line-breaks. We've also used indentation to line-up all the keys and all the values within the initial array assignment. Again, this is not required, but it does help to improve code readability.
You should also notice that we're separating each key and value with the double-arrow operator =>. This is PHP's way of saying a string key has a specific value - you'll use it in your own code a lot when dealing with arrays, but you'll also see it in the output of var_dump().
You can see that we can also use square bracket notation with string keys to reference a specific element much in the same way we did with numeric keys. The code above will result in array with 4 elements, the keys are 'foo', 'toto', 'pippo' and 'aap' and their respective values are 'bar', 'titi', 'pluto' and 'noot'. You can see this in the output from var_dump which you will get if you run the program:
array(4) {
["foo"]=>
string(3) "bar"
["toto"]=>
string(4) "titi"
["pippo"]=>
string(5) "pluto"
["aap"]=>
string(4) "noot"
}
That's enough on arrays for now, but we will revisit these in greater detail in later chapters.
Digital Crocus offer affordable UK web hosting to get you up and running from just $32.49 per year or $3.99 per month. Our most basic account would be enough to get started learning PHP and host a few websites with a moderate amount of traffic. We offer easy upgrade options as your requirement grows and a friendly and helpful email and phone customer support service. If you're looking to buy web hosting, consider giving us a try - under our money back guarantee we'll refund you if you're not 100% satisfied.
Kieran Simkin is an experienced software developer and co-founder of Digital Crocus. Kieran is also a keen amateur photographer and musician and has a personal portfolio which you can see online.