PHP Variables

Chapter 5 32 mins

Learning outcomes:

  1. What are variables
  2. Creating variables in PHP
  3. Rules for naming variables
  4. Tips for naming variables
  5. Dynamically-typed nature of PHP
  6. Variable variables
  7. Determining a variable's existence using isset()

What are variables?

A variable is a very abstract idea in the world of programming languages, yet it's so fundamental that no single high-level language today exists without it — it's just impossible to even imagine that!

But what exactly is a variable?

Well, as we described in the last chapter:

A variable is a container to hold some piece of data.

Now this is an easy definition and one that doesn't at all express even the outskirts of how variables really operate under the hood in a computer language. It's clearly not wrong — just a bit easier and less practical.

The definition that does express the reality of variables is in terms of memory:

A variable is a name referring to a location in the computer's memory where data can be stored.

All of the data that we store inside a variable in PHP is stored in the computer's memory.

We can retrieve the data, change it to something else, use it in other expressions and so on.

Variables allow us to effectively give purpose to data stored in memory and in this way help us work with it extremely easily. For instance, the variable $password in PHP helps us to store a user's password in memory and, at the same time, be aware of the fact that it is the password of the user.

Imagine if instead of names, we had to use numbers such as 1, 2, 3, and so on, to store and retrieve data from memory. In that case, the username might be in variable 1, the password might be in variable 42, the total cost of the shopping cart might be in variable 30, and ...

Well, you obviously get where we are heading to, don't you?

The concept of variables isn't native to computer science — it existed way long before it. Variables are a paramount part of mathematics. They are used all over this humongous field of numbers and theories.

It was just very natural to go on and use the same idea in programming languages; just this time not to only hold numbers, but nearly any datum.

Creating variables in PHP

To create a variable in PHP, we use the following syntax.

$<name> = <value>;

Note that this is a template syntax, not a concrete example. <name> and <value> are ought to be replaced with real code. Note that there must be no space between $ and the given <name>.

Let's create three variables holding the numbers 1, 10 and 100, respectively.

<?php

$x = 1;
$y = 10;
$z = 100;

Each statement here creates a new variable and thus buys some amount of memory to store the given value. This stage is effectively as variable definition i.e it defines a variable.

Storing a value inside a variable (i.e. the variable followed by = followed by the value to put inside it) is known as variable assignment. That is, we assign a particular value to the variable.

Once defined, using a variable is as simple as prefixing it with the $ symbol.

For instance, in the code below, we add all our three variables $x, $y and $z and print the result:

<?php

$x = 1;
$y = 10;
$z = 100;

echo $x + $y + $z;
111

Simple!

As expected, it's possible to change the value stored inside a variable; or said another way, it's possible to perform multiple assignment operations on a variable.

In fact, that's why we call them 'variables'.

Consider the code below:

<?php

$x = 1;
$x = 10;

First $x holds the number 1. Then after the statement in line 4, it holds the number 10. Clearly, the value of $x has changed.

Line 3 here is a variable assignment statement that also defines the variable $x. Line 4 is just a variable assignment statement and doesn't define $x (it has already been defined).

Moving on, as we specified in the previous chapter, a variable's name is sensitive; hence $x is not the same thing as $X.

In PHP, when we use a variable that doesn't exist, we get an error. This is an example of a semantic error i.e. the code doesn't make sense (although it may be syntactically legal).

An example follows:

<?php

$x = 1;
echo $X;
Warning: Undefined variable $X in <path> on line 4

We define a variable $x but later on refer to it as $X (with a capital 'X'), and this leads to an error.

Such errors could, and usually do, creep up in programs mainly from typos. It's impossible to completely elimiate them, but at least if you see a similar warning next time in your code, you know what to do.

Are the variables $name and $namE the same?

  • Yes
  • No
Definitely, they are not the same. The last character 'e' is different in both the variables.

Rules for naming variables

Almost all programming languages enforce certain rules on the programmer when naming variables. This is done to prevent programmers from naming variables in ways that could introduce ambiguity into programs.

PHP is no way behind — it has a couple of rules as well. These rules are quite standard ones and used in many other programming languages as well.

The rules we must follow when naming variables in PHP are as follows:

  1. Names can't begin with a digit. Hence, $2nd is wrong.
  2. Names can only contain alphanumeric characters (a-z, A-Z, 0-9) and the _ (underscore) character; nothing else.
  3. Names can't contain spaces. Hence, $first word is wrong.

You might be wondering as to why are these rules imposed on a programmer. Well, it's superbly easy to reason.

Tips for naming variables

In the discussion above, we saw the rules laid out by PHP for naming variables. Having just a small set of characters to choose from, variable naming is an art, and one of those that can take our program way long into the realms of high readability.

In the following section, we discuss a couple of tips to consider when naming variables, including which casing convention to use.

Be descriptive

A variable's name shall clearly describe what it's meant to hold.

For instance, suppose that you have to store a user's name in a variable. It would be really bad if you name the variable $a (or $x or $u for 'user', or any random character). The name $a doesn't tell much about what's stored in the variable.

A much better name would be $username, or $uname.

Well frankly speaking, the latter, i.e. $uname, is less descriptive and sometimes could be ambiguous — $uname could also stand for 'universal name', 'unsatisfactory name', or maybe even 'unique name'.

Don't be too descriptive

But hold on to your descriptive naming skills — you don't want descriptive names that just never end.

Suppose we want to create a variable that stores the first name of a user. Being exceptionally descriptive, we could name it $thefirstnameofuser, although this would be more than the required amount of description.

A better name would be $firstname.

We have to remain in between the scale of descriptiveness — not too little, and not too much.

Abbreviate long words

Sometimes, it's really helpful to abbreviate long words in a variable's name to short words, given that the abbreviation seems sensible.

For example, the variable $dbname could work well instead of $databasename. Here, we've abbreviated 'database' to 'db'.

The abbreviation 'db' for 'database' is quite a common one out there.

But keep in mind that abbreviations don't always work well.

For instance, naming a variable that holds the name of an object's property as pname, instead of propertyname would be a complete mess. pname could mean 'property name' or 'panel name' or 'previous name'. A much better name would be propname — with the word 'property' abbreviated down to 'prop'.

Use a casing convention to break words

When a variable's name contains more than one word, it's desirable to use some casing convention to be able to distinguish between them easily while reading the variable.

Let's say you have a variable questionsasked that holds the number of questions asked in a quiz program. Seeing this name doesn't right away tell us about the individual words in it. We have to gaze at it for a while until we realise that it says 'questions asked'.

Worse yet, in some words the name could even be misinterpreted by the reader. For example, what can you read in idenum? Did you read it as 'ide num' or as 'id enum' ?

Well, the variable meant 'id enum' for 'ID enumeration'.

So to solve such ambiguities and make long variable names readable, we use casing conventions.

Some common casing conventions are as follows:

  1. camelCasing: every word's first letter is uppercased except for that of the first word. Camel casing is the casing used in JavaScript. Here are some identifier names from JavaScript: indexOf, getElementById, querySelectorAll.
  2. PascalCasing: every word's first character is uppercased. C# uses Pascal casing for almost all identifiers. Some examples from C# are as follows: WriteLine, ReadLine, GetType.
  3. snake_casing: every word is lowercased and separated from the other using the _ (underscore) character. PHP uses snake casing for most of its predefined functions. Some examples from PHP are as follows: array_push, mysqli_connect, str_split.
  4. SCREAMING_SNAKE_CASING: every word is uppercased and separated from the other using the _ (underscore) character. This casing is commonly used to denote constants in many programming languages, including PHP. Some examples from PHP are: PHP_VERSION_ID, E_ALL, DEFAULT_INCLUDE_PATH.
As we shall see later in this course, identifier names could not only describe the data they point to, but also to what the identifier itself is i.e. is it a class, a constant, a method and so on.

Coming back to our example, the variable questionsasked could be renamed to one of the following:

  1. questionsAsked
  2. QuestionsAsked
  3. questions_asked
  4. QUESTIONS_ASKED

Now it doesn't require much effort on our side to comprehend what exactly is the name of the variable trying to say. All the individual words are recognizable at the first glance.

But which one of these should we use?

Which casing convention to use in PHP?

Well the two most common conventions used when naming variables in most of the programming languages out there are camel casing and snake casing.

The question of 'which convention to use in PHP' really boils down to the question of 'whether to use camel casing or snake casing in PHP'.

Now, if we look into the code bases of some PHP libraries out there, we notice usage of the camel casing convention. However, most of PHP's core functionality uses snake casing.

So honestly speaking, this is solely a matter of preference. If you like camel casing, go with it. Similarly, if snake casing appeals you, go with it. Whatever you choose, make sure to stick with it — consistency is a must!

In this course, we'll use the snake casing convention simply because much of PHP uses it.

To boil it all down, naming isn't any theory to master — it's purely an art.

In your journey of programming, you'll be able to come up with extremely effective variable names with:

  1. Experience — the more you code, the better you become at naming.
  2. Lots of trial and error — keep on altering the name of the variable unless and until you think it communicates its purpose in the best way.

Dynamically-typed nature of PHP

Before we can move on with other goodness of variables in PHP, we need to understand one highly important charactertic of the language — dynamic typing.

The category of high-level languages such as C, C++, Java, Python, PHP, Ruby, etc. can be further divided into groups based on the fact as to whether they have a static type system or a dynamic type system.

Languages such as C, C++, and Java are usually known as statically-typed languages. This means that variables in these languages have types, those types are known right when reading the source code, and prevent variables from being assigned to values of incompatible types — for instance, a variable meant to hold integers can't hold strings.

This is the opposite of what languages such as PHP, Python and Ruby are. They are called dynamically-typed languages.

This means that types in these languages are determined at runtime, reading the source code can't help us determine the types of variables, and variables can transition between different types during program execution.

Dynamic-typing isn't always desired!

You might be thinking that this dynamic behavior is rewarding. Well, it actually is, but NOT in all cases.

In 3D rendering engines, or graphics-intensive application, or any program where even the tiniest microsecond of performance matters, dynamic typing is an undesirable feature.

Moreover, sometimes a static type system is deliberately desired such as in large-scale applications where hundreds of developers are collaborating simutaneously. This is done to impose strict programming rules on programmers and ensure consistent programming.

Dynamic type systems come with an overhead in memory for every variable that we create.

So where does this overhead come from?

Well, the underlying engine parsing a dynamically-typed language's source code (such as Zend) can't determine what would eventually be stored inside a variable at any instant, and hence couldn't allocate the size of an integer, or maybe a float to that variable.

Instead what the engine does is that it allocates the largest size amongst all possible values in the language (which are usually not that much) to the variable, so that it could store an integer, a float, a string, and obviously the largest datum.

This, as is evident, wastes memory when we store something of a smaller size in that variable.

Anyways, coming back to PHP, since it's dynamically-typed, operations such as the following are possible:

<?php

$x = 10;
$x = 'Hello';
$x = -0.5;

Here we create a variable $x with the integer value 10. Then we change it to the string 'Hello'. Finally, we change it to the float -0.5.

All this is possible only because of the dynamically-typed design of PHP. Had it been statically-typed like C, C++ and Java, it would've been impossible to make such changes.

Variable variables

One of the nice features of PHP and one special to PHP only is that of variable variables. Seems quite a fancy term.

So what are variable variables?

A variable variable is a variable whose name is taken from another variable's value.

This allows us to name variables dynamically.

A variable variable is denoted the same way as an ordinary variable except for that the name of the variable is given as another variable. Hence, in one way, we could say that a variable variable is denoted using $$.

Consider the code below:

<?php

$name = 'greeting';
$$name = 'Hello World!';

echo $greeting;
Hello World!

First, we create a variable $name holding the value 'greeting'. Next, we create another variable $$name and set it to the 'Hello World!'. Finally we output the variable $greeting.

Now although we didn't literally define $greeting in the code, it does exist. This comes from the $$name variable variable defined in line 4, where $name gets replaced with greeting in $$name to ultimately give us $greeting.

What does the following code output?

<?php

$greeting = 'Hello';
$$greeting = 'World!';

echo $hello;
  • Hello
  • World!
  • It throws an error
The code throws an error since there is no variable such as $hello. There, however, is a variable $Hello which is created in line 4.

Determining a variable's existence

It's not a rare thing to check for the existence of a variable in PHP before using it.

When you move on to develop complex applications, whereby multiple PHP scripts call one another, chances are that you might want to read some variables defined in another file. In that case, there might be certain instances when the variables might not be defined at all in those files.

Referring to these variables as it is in another PHP script can be problematic.

Now, it's your time to reason why?

Well, recall that referring to a non-existent variable in PHP throws an error. This is the exact problem — we aren't sure whether the variable is defined or not and so accessing it directly could lead to an error.

To prevent running into such a problem, we ought to check whether the variable exists before using it. And that's done via the isset() function.

The isset() function determines whether a given variable is set.

Here's how to use the isset() function:

isset($var)

The isset() function returns a Boolean to signify whether the variable exists or not.

So what's a Boolean?

What is a Boolean?

A Boolean is a true or false value that's used most commonly in conditional programming — executing code based on given conditions.

The name Boolean is given in honour of the prolific English mathematician George Boole who's generally considered as the father of symbolic logic.

In PHP, the two literal Boolean values are true and false. In the code below, we create two Boolean variables:

<?php

$is_reading = false;
$is_learning = true;

As we shall see later in the PHP Control Flow unit, these values are used when executing code conditionally.

If we echo true, a 1 is shown in the console; if we echo false, nothing is shown.

If you read the last sentence in the snippet above detailing about Booleans, you might realize that it isn't possible for us to print the return value of isset() for effective inspection.

That's because the function returns a Boolean and when that's false, nothing is printed in the terminal.

So how to make sure that false also shows up in the output? Well, we can use another logging function — var_dump().

var_dump() prints a value along with its type information.

var_dump() also prints a newline character in the end so that successive calls to var_dump() don't need to have a newline character's printing in between.

Let's test the function:

<?php

var_dump(10);
int(10)

As you can see, var_dump(10) prints int(10). This means that 10 is an integer with the value 10, trivially.

Alright, time to go back to isset() an test its return value on an undefined variable using var_dump():

<?php

var_dump(isset($non_existent));
bool(false)

Here's how this code works...

First, the call isset($non_existent) is resolved. Since there is no such variable as $non_existent, the function call isset($non_existent) returns false. Hence, in the second step, what executes is merely var_dump(false).

This ultimately prints bool(false) to the terminal, confirming that yes there really is no such variable as $non_existent.

Let's try this same code on a defined variable:

<?php

$existent = 0;
var_dump(isset($existent));
bool(true)

As can be seen, this time we get bool(true) returned signifying that $x was surely set.

isset() also checks for NULL variables!

As we shall see later on in this course when we explore the value NULL, isset() also checks whether a variable is not NULL.

That is, if a variable exists but its value is NULL, isset() would treat the variable just as it would treat a non-existent variable, i.e. return false:

<?php

$existent = NULL;
var_dump(isset($existent));
bool(false)