LEARN PHP IN A DAY: The Ultimate Crash Course to Learning the Basics of PHP in No Time (2015)

Chapter 2. Variables

Introduction to Variables


In PHP, variables are declared using the dollar sign($):

This declares, or creates, the variable. Important to note is that before you create the variable, it is considered unset. It doesn’t exist. Kind of intuitive, but this can sometimes lead to some unexpected errors as we are going to see later on.

Here we have created astring variable (note that we don’t declare the type). We’ll look at the different variable types a bit later in this chapter.


              There are rules to keep in mind when creating variables inside of PHP. We’ll list all of them and after that we will take a look at code that shows these. Here are the basic rules:

·      Variable names start with a letter or underscore;

·      Variable names cannot start with a number;

·      A variable name can have any number of letters, underscores of numbers;

·      Valid letters are all ASCII hexadecimal letters from 00 to FF;

Let’s take a look at an example of code declaring variables:

If we test our file we will get the following error message:

This tells us that we have an error in declaring our variable.

Variable Types and Typecasting

              Unlike many other languages, PHP does not require you to explicitly declare the variable type, rather, it determines it from the context. In other words, you don’t have to explicitly tell PHP whether you want a variable to be a double precision number or a string.  To help you imagine this, you can think of variables as boxes. Imagine a row of lockers (like the kind you would see at an airport or a train station). Each locker represents a variable. Each locker has its own unique number, which differentiates it from all of the other lockers. If someone tells you to open locker number 42, you would be able to find it without a problem and you wouldn’t confuse it with any other locker (for example 24). In a similar way, PHP variable names are unique and each PHP variable is unique. Now, you open locker number 42, and you see that it is empty. You move on to locker 43 and see that there is a package inside it. You take the package from 43 and place it in 42. Before opening the lockers you didn’t know what was in the lockers. After checking, you know what is contained inside that locker and you can manipulate it as desired. In a similar fashion, variables in PHP can contain anything you place in them. Essentially, when you are checking the type of a variable, you are checking the type of the content inside of the variable.

              That explanation may be a bit confusing, but you’ll get used to it very quickly and you will not have problems dealing with variables in PHP. Let’s take a look at some of the variables inside of PHP:


              Booleans are the simplest type of variables that exist in PHP. Booleans are used for logical statements and to express a truth value. Booleans are binary, meaning that they take one of two values:TRUEorFALSE. Having said that, let’s look at an example of a Boolean variable:

              Like many other languages, PHP is flexible in its use and interpretation of Boolean variables. In other words, we can create Booleans without explicitly defining them as either being TRUE or FALSE. IN fact, here is the list of rules that determines which values are considered to be FALSE by PHP:

·      The BooleanFALSE;

·      The integer0;

·      The float0.0;

·      The empty string and the string“0”;

·      An array with zero elements;

·      The special typeNULL;

·      ASimpleXML object created from empty tags;

Everything else will returntrue;

This means that if we can write the following code and it will be valid:

Even though we still haven’t covered if statements, you can pretty much figure out what will happen here. The implicit Boolean variable is defined inside the parenthesis (). Once the logical operation executes it will return either a TRUE or a FALSE.

A couple of important things to note about the above example:

PHP considers the integer 1 to be the same as TRUE. That means, if we have defined the variable ‘var’ to be TRUE, and we check it against the integer one, the logical statement will return TRUE:

The second thing to note:

We are using a double equals sign to check whether one value is equal to another. Don’t make the mistake of using a single equal sign.

After all of that, we should introduce typecastingTypecasting is when we take the value a variable and we convert it from one type to another. For example, we can have a variable with a value of 42 and we want to cast it to a Boolean. Another example is if we have a variable with the value of 42 and we want to cast it to a string (more on that later). For Booleans, type casting is for the most part unnecessary (i.e. you will almost never ever do it). This is because values will automatically be converted to Booleans if an operator, function or control structure requires a Boolean as argument. However, for the sake of consistency with the other type casts, this is how to cast a variable to a Boolean:


Numbers in PHP, and most programming languages, come in different flavors. The two subtypes of numbers in PHP are Integers and Floating point numbers. Let’s take a look at each one.


By definition,  integers are all numbers in the set:

In other words, integers are all whole, real numbers (both positive, negative and zero). PHP allows us to define integers in a number of ways. You can define integers in base 10, base 8 (octal), base 16 (hexadecimal) or binary (base 2).In order to use octal notation for an integer, you need to precede the number with a0. To use hexadecimal notation for an integer, you precede the number with an0x. Lastly, if you want to use binary notation, you precede the number with0b. Here is an example:

Take note of the last function we use (don’t worry if you don’t know what functions are).

Helpful Tip!

You can check the type and contents of a variable by usingvar_dump(). The function takes one input as an argument (again, don’t worry if you don’t fully understand. This means that you should only put one thing inside the parenthesis). The function will print the type of the variable and the contents to the screen. In the above example, the output to the screen will look like:

Now try to usevar_dump on the other variables. Do you notice anything interesting? Do you see the value that is being printed to the screen for each variable? What base is it in?

The largest number that can be stored on a 32-bit system as an integer is of magnitude 21474783647. Anything larger than that will automatically be converted to a type offloat. For a 64-bit system the number is of magnitude 9223372036854775807. Anything larger than that will automatically be converted to a type offloat.

If you want to convert a variable to an integer, in other words cast it as an integer, you would do the following:

This type of casting is useful in a number of situations, but the most common usage is for security. One of the exercises at the end of the chapter will show you a particular usage of integer casting for security purposes.

Floating Point Numbers

              Integers was the set of real and whole numbers, so logically, floating point numbers (also referred to as “floats”, “doubles” or “real numbers”) will include everything else. That is, the numbers that in between integers. Thus, we get the set of all real numbers. With that being said, it is crucial to note that all computers have a limitation as to the precision with which they display numbers (this is known as a machine epsilon). Furthermore, there are some weird discrepancies that may occur when dealing with floats. We won’t go too much into that since it is beyond the scope of this book, but if you find any non-intuitive results when dealing with floats, think about the precision with which PHP handles floats.

Floats can be represented in the following ways in PHP:


Stings in PHP are series of characters. You use these to store pieces of text and words. PHP handles each character as a byte. With that being said, we should note that the largest string that PHP can support is of size 2GB. The fun bits come when defining strings.

Single quotes

The easiest way to define a string in PHP is to use single quotes.

What happens if we want to incorporate new lines in our string?

This is valid syntax inside of PHP, but the newline break will not be incorporated into the final output. Not the use of theecho function. What does the above code output?

Helpful Tip!

You can use theecho command to output strings to the screen. In fact,echo can be used with any of the variable types to output their contents other than thearrayandobject types. This is very useful tool for debugging and you should often use it when you need to check something quickly or to find errors in your code.

OK, now imagine you want to input a string that contains a single quotation mark. What do you think the output is going to be?

You can probably tell even from the syntax highlighting that this is not going to work. Every time PHP encounters a single quotation mark, it will either start or end a string variable. In order to store a single quotation mark, we need to escape it. In PHP, this is done using the backslash. The same thing will happen if we want to include a backslash. We have to escape it with another backslash:

Useecho to see the results above. Keep in mind that a backslash is used for escaping.(This means that\n will not render as a newline)

Another thing that cannot be used inside single quotation marks is variables. For examples, the following will not expand inside of single quotation marks.

This will not display “Her name is Katherine” as you would expect.

In order to make the above example work, we need to concatenate the variable and the string. In PHP we would do the following:

Test out the above code and confirm that it works.If you want to continue the string after the variable, you just concatenate the next string to the variable. In other words you use$str.’your string here’. This works as long as the variable can be cast into a string (PHP does that automatically for you in this case).

Double quotes

This is the more complex way of defining strings in PHP, but it gives you a lot more control and flexibility. In the previous examples, we saw that \n, \t, \r and similar will not work in single quotes. This is not the case with double quotes. Double quotes allow you to use those special symbols.

The most useful thing about double quotes, however, is their ability to parse variables. There are two ways to parse variables inside of double quotation marks.

              Simple variable parsing

The simple way to parse variables is by just using the dollar sign inside of your string:

You can use this same concept if you want to reference elements of an array. (You should probably come back to this section after reading about the next variable type).

              Complex variable parsing

This is called complex because it allows you to create more complex expressions, not because the method itself is complex. This method requires you to use curly braces around your variables.

You can expand this and test it out on things such as arrays, objects and functions once you learn about those.

String casting

As with all other variables, we can cast variables to strings. To do this you use the(string) function.  PHP will automatically convert variables to strings depending on the scope of the expression and if a string is required. For example, if you useecho on a variable, it will first convert it to a string.Numbers will be converted to their textual representation. This means that10will become“10”. Arrays and objects behave a bit differently, though. If you useechoon anarray, you will get the string“Array”. Similarly, if you use echo on an object, you will get the string“Object”.


An array is a type of ordered map. What this means is that arrays will associate values to specific keys. Arrays in PHP can be used to represent dictionaries, vectors, lists, stacks, queues, trees and multidimensional arrays (arrays of arrays).

Arrays are created in the following way:

Note how we have used indentation for the sake of clarity. The extra whitespace is ignored by PHP, but it makes our code easier to read and manage.

Each line of the array represents a key-value pair. Each line ends with a comma to indicate the next key-value pair in the array. The last entry of the array does not need to have a comma at the end of it, but most people like to include it. This convention is adopted by many people dealing with content management systems such as WordPress, Drupal and others. (The idea of leaving the comma is that you can take the entire line of key-value pairs and move it around in the array without having to worry about including a comma).

The keys of an array can be either integers or strings. If you use something else for the array key, it will automatically be cast into either of these types. (NOTE: arrays and objects cannot be used as array keys as this will result in an error).

Alternatively, you do not need always need to supply the key. You can do the following:

This will create keys for you automatically by incrementing each key, starting from 0. We can check the contents of the array:

You can see that the first entry of the array starts from key 0. It is important that you remember that the first value in an array with default keys is always going to be stored under key 0.

You can reference elements of an array using the square brackets.

Play around with this syntax and try to create arrays of arrays (multidimensional arrays). In other words, try to have an array as the value of some key. This looks like:

You will get a chance to practice this in one of the exercises.

If you want to create new elements to an existing array, or to modify elements of an existing array you use the square bracket syntax:

The above outputs:


Objects will be an object of discussion in Chapter 10 and we shall leave them for now.


The NULL value is special and it represents a variable with no value. The only possible way of that happening is if the variable is assigned the constant NULL, the variable has not been assigned a value yet, or if the variable has been unset (remember the last example from the array section when we unset the value of the 2nd entry).


This is the end of this chapter! You learned a lot about PHP and how it works. You’ve taken your first steps, steps that you will use over and over again when writing code. This chapter may have been a little boring in some bits, but it is important you learn these basics well so you can apply them without having to think about it later on. Here are some exercises to get your gears going and get you thinking about using what you’ve learned.

Exercise 1

You are given the following array of user data. Perform the specified manipulations to it:

1.                Create a string that consists of the first and last name of the user by concatenating the values from the array.

2.                Suppose that this array will be stored into a database of other users. We want to make sure that all values will be of the correct type.

1.                   Cast the user ID to a type of integer;

2.                  Cast the admin field to a type of Boolean;

3.                Add a new field with a key of‘email’ and set it to the value of: ‘john.doe@example.com’.

Exercise 2

Create a menu for a restaurant. To do this, you have to use a multidimensional array. Your menu has to include three main subcategories (name your arraymenu and the keys inside this array will be your main subcategories). Each subcategory will include 4 meals/foods. For each meal/food you need to include a list of ingredients and a list of nutritional information (carbs, sugars, protein, etc.). You have to figure out the most efficient way to do this inside of PHP. (Hint: Think about how you want to create and organize the information for each meal. Do you want to make the key the name of the meal, or do you want to set the key to be automatically incremented and include the name of the meal inside the array? Which makes the most sense to you? Which causes the least confusion? Sketch it out on paper if need be).

Exercise 3

Imagine you are creating an online application for a restaurant and you are tasked with creating the section for deliveries. Use the array from the previous exercise to provide yourself with the data for the menu. Create a variable that represents one of the three main subcategories (it should have the same exact name). Now create a variable that corresponds to one of the foods you made. Suppose that these variables represent the choice made by a user when selecting their meal.

Create a string that would be a message displayed to the user with important information about their order. It should look like this:

You picked: {name of meal here}.

This meal is made from: {list ingredients here}.

The nutritional information for this meal is: {list nutritional information here}.

Think about concatenation, single vs. double quotations, array referencing.