Now we're getting to the meat and potatoes! Variables are an extremely useful and well abused part of the developers toolkit. Let's get started, shall we?
Tiny Boxes
I'd like you to think of variables as tiny little boxes that we keep things in. Variables are words that start with a dollar $
sign. Let's take a look at an example.
<?php
$three = 3;
If you think of the variable $three
as a little box, then we've put the value 3
into it. That's what the equals sign does. In math we use the equals sign to indicate the result of an equation, however, in PHP it's an entirely different story.
In PHP the equals =
sign is known as the assignment operator. It's used to set something. We are telling PHP to set the variable $three
to the number 3
.
If you execute the script we have created above, you'll find that PHP doesn't output anything at all. This is because assignment is purely assignment. We aren't telling PHP to output anything. However, now that we have set the variable $three
to the value 3
, we can use the echo
construct on it.
<?php
// Set our variable to the value three.
$three = 3;
// Output the value of our variable.
echo $three;
First we set our variable, and then we use the echo
construct to output the value that it's holding. If we execute our code, then we receive 3
as output.
This is great because it means we can give nicknames to things. You know, just like those mean kids at school. For example, the number '3.14159265359' is a very beautiful number to lovers of circles, but it's awfully hard to remember, isn't it? Let's give it a nickname. We'll call it Pete. No wait, I have a better idea.
<?php
$pi = 3.14159265359;
There, now we have created a new variable called $pi
that holds the value 3.14159265359
. This means that we can use the variable anywhere in our code to perform calculations. Here are some examples.
<?php
// Assign pi to a variable.
$pi = 3.14159265359;
// Perform circumference calculations.
echo $pi * 5;
echo $pi * 3;
After setting $pi
, we can use it in other statements to perform calculations.
We can declare and assign as many variables as we like, but there are a number of rules that we need to follow when choosing names. Variable names can contain numbers, letters and underscores. However, they must start with either a letter or underscore, never a number! They are case sensitive, which means that $panda
is different to $pAnda
. Here are a few examples.
<?php
$panda = 1; // Legal
$Panda = 1; // Legal
$_panda = 1; // Legal
$pan_da = 1; // Legal
$pan_d4 = 1; // Legal
$pan-da = 1; // Illegal
$4panda = 1; // Illegal
While variable names can contain underscores and start with capitals, it's a common practice to use a naming format known as camelCasing
. Don't worry, it doesn't require a camel.
camelCased names start with a lowercase character. Variables that are to be named with multiple words will have the first character of subsequent words capitalized. Here are some examples.
<?php
$earthWormJim = 1;
$powerRangers = 1;
$spongeBobSquarePants = 1;
Do you remember how our statements return a value? Well our assignments are also statements. Can you guess what this means? That's right, they also return a value. We can prove this by using our good ol' friend the echo
construct.
<?php
echo $panda = 1337;
We receive the number 1337
as the output. This is because the assignment of the $panda
variable is performed before it is outputted. This process allows us to use a clever trick. It's not something you're going to use very often, but I think it's a pretty cool trick to know. Go ahead and take a look at this example.
<?php
$firstPanda = $secondPanda = $thirdPanda = 1337;
The snippet above might look a little crazy, but it makes more sense if you read it from right to left. The $thirdPanda
is assigned the value 1337
, next the $secondPanda
is assigned the value of $thirdPanda
, and finally the $firstPanda
is set to the value of the $secondPanda
. This means that all variables are set to the final value. Neat, right?
Just my type
Until now we have been working with numbers. It would be boring if those were the only types of values that we can use, right? I think it's about time we examined the other possibilities. Here are some of the common values used within PHP applications.
- integer
- float
- boolean
- string
- null
- array
There are a few more, but let's not complicate matters right away. We need to learn little by little. You don't want knowledge overload!
Let's take a look at these types one by one. First we have integers. These are whole numbers, we've been using these in our previous examples.
<?php
$panda = 2;
$redPanda = -23;
Floats are floating point numbers. They have decimal points, and thus contain fractions. They can be used in a similar fashion to integers. In fact, we've used one already. Do you remember our friend $pi
? That was a float. Let's move on to something new shall we?
<?php
$panda = 2.34;
$redPanda = -23.43;
Booleans are binary data types. No don't panic! We aren't going to do any binary arithmetic. It's just a way of expressing that they can be one of two values. A boolean can either be true
or false
. Later on, we'll take a look at how boolean values can be used to change the flow of our application.
<?php
$panda = false;
$redPanda = true;
Next up we have the 'string' value. Strings are used to store a word, a character, or a sequence of text. Strings are special, so I've decided to dedicate a short chapter to them. We'll come back to this!
<?php
$panda = 'Normal Panda';
$redPanda = "Red Panda";
Null is a special value. It is nothing. Nil. Zero. Well actually it's not zero. Zero is numeric, and we can use integer for that. Nulls are exactly nothing. Null is the value that a variable has before assignment has been performed. It's a really useful value, and you're going to see a lot of it in the future.
<?php
$noPanda = null;
Arrays are another special type of value. In fact, this is my favourite one of all. So much that I've decided to dedicate a full chapter to them. For now, all you need to know is that it's a value that holds a collection of other values. Woah! Inception stuff, right?
<?php
$countThePandas = [1, 2, 3];
$morePandas = array(5, 6, 7, 8);
Advanced Assignment
In a previous chapter we discovered the operators that we can use on variables, and we've mastered the assignment operator. So what happens when we put them both together? Will it create a new black hole and consume the entire universe? I'm feeling a little daring, shall we find out?
<?php
// Set a value.
$panda = 3;
// Attempt to create a black hole.
$panda += 1;
// Universe withstanding, dump the value.
var_dump($panda);
First we set a variable to the integer value of three. Next, we've plopped the addition operator onto the front of the assignment operator and supplied another integer value of one.
We can use the function var_dump()
(more on functions later!) to interrogate not only the value held within a variable, but also its type!
What did we get back from the dump?
int(4)
Awesome! The universe is saved. It looks like we have a four? Well, I suppose that makes sense. We know that $a + $b
returns a value without setting it, and we know that the assignment operator is used to set the value of variables. This does both. We're telling PHP to set the value of $panda
to its current value plus one.
You can use this syntax with any of the operators that we've discovered so far. There's only one catch. Don't place the operator on the other side of the equals sign. Trust me, I tried it. A portal opened to a dark underworld, half dinosaur, half human creatures broke through and began to terrorise Cardiff. Only with the aid of a home made flamethrower (powered by PHP) was I able to fend off the vicious creatures. I'd hate to see it happen to you. Please be careful!
Next up, we have the incremental operator. Actually, let's not forget the decremental operator too. She tends to get a little less attention. In fact, let's showcase her abilities.
I prefer to lead with an example. Consider the following snippet.
<?php
// Set a value.
$panda = 3;
// Decrease the value.
$panda--;
// Dump the value.
var_dump($panda);
There in the middle, do you see her? The beautiful decremental operator. We simply place two minus signs after the variable. What does it do? Well, here's the result of the code snippet.
int(2)
As we can see, the value of $panda
has been decreased by one. It's a quick shortcut to decreasing a value. Likewise, using a ++
can be used to increase a value. Those are the only two operators that work, though. Don't you be cheeky and try use the multiplication operator. It just won't work as you expect it to!
I wonder what will happen if we put the operator before the value? Let's have a go, shall we?
<?php
// Set a value.
$panda = 3;
// Decrease the value.
--$panda;
// Dump the value.
var_dump($panda);
What's the answer? Aren't you excited?
int(2)
Oh, it's the same. Well that was rather boring, wasn't it? Actually, I know a little secret. It's not the same. Sure, the value we received back looks identical, but my example doesn't do it credit.
Let's craft a different example. We'll show the state of a value before the operator is used. We'll examine the result of the statement when the operation is used, and finally, we'll examine the value after the operator is used. We don't expect the after-value to be any different.
<?php
// Set a value.
$panda = 3;
// Dump BEFORE.
var_dump($panda);
// Dump DURING.
var_dump(--$panda);
// Dump AFTER.
var_dump($panda);
Let's execute the code. What are the three values we receive?
int(3)
int(2)
int(2)
The first value is three. We must have expected that, I mean, all we did was set it, right? The result of the statement using the decremental operator is equal to two. The resulting value is also two. That means that the value is decreased on the second line.
Let's move the operator to the other side of the value, shall we? Like this:
<?php
// Set a value.
$panda = 3;
// Dump BEFORE.
var_dump($panda);
// Dump DURING.
var_dump($panda--);
// Dump AFTER.
var_dump($panda);
Look very closely to spot the difference. Let's take another look at the result.
int(3)
int(3)
int(2)
Hey!? That middle value is different! Why hasn't it been decreased? Well, by swapping the operator, we've told PHP to decrease the value AFTER the current line. The result of the operation line is the same value as it was initially.
Let me summarise.
$value-- - Change value *after* current line.
--$value - Change the value on the current line.
Why is this useful? Well, here's a use for you. I'm sure if you're creative you will find more. Using the operator that changes after the current line, we can set another variable to its value, and decrease the original value on the same line. Like this:
<?php
// Set a value.
$panda = 3;
// Assign, and then increase.
$pandaFriend = $panda++;
What we've done here, is saved a line. It's a bit of a shortcut. Here's how it would look if not for the incremental operator.
<?php
// Set.
$panda = 3;
// Assign.
$pandaFriend = $panda;
// Increase.
$panda = $panda + 1;
In a later chapter about loops you'll find another use for this operator. In the next chapter we'll be taking a closer look at strings.
My books are available online for free to encourage learning. However, if you'd like for me to keep writing, then please consider buying a digital copy over at Leanpub.com.
It's available in PDF, ePub, and Kindle format, and contains a bunch of extras that you won't find on the site. I have a full-time job, and I write my books in my spare time. Please consider buying a copy so that I can continue to write new books from the comfort of my sofa!