Variables are important in every programming language — and it’s no different in PHP. Variables give developers the possibility of temporarily storing data to be used in PHP scripts (in PHP’s case, this happens in the server’s memory). This guide is all about working with variables in PHP.

By the way, if you are just starting out with PHP, I recommend reading this guide first: Learning PHP: Get Started Using PHP.



Comment, Comment, Comment!

Before we start, I’d like to introduce you to PHP comments. As a developer, you should try to comment your code in such a way that your code logic is explained well; this is one of the good habits coders should have.

Without even looking at the PHP code, you know what this function is capable of just by reading the comments (in green).

How Does Commenting Work?

One way of placing a comment in one line is achieved by having two forward slashes (//) preceding the comment.

Another way to make comments is through a comment block which is wrapped by /* */. You want to use a comment block when your comment is more than a few lines long.

Another way — which is rarely used nowadays — is using a hash symbol (#) in front of the comment.

PHP and Variables

A PHP variable always starts with a dollar sign ($).This is just to let the PHP parser know that we are dealing with variables. You should always try to give your variables names that are as descriptive as possible.

Alphanumeric characters (i.e. A-Z, a-z, and 0-9) and underscores (_) are allowed, but the name cannot start with a digit. If your variable contains other characters or if it starts with a digit, it will produce a parse error.

A variable name without a dollar sign ($) in front, or a variable name that contains invalid characters will most likely result in a parse error.

PHP aborts the parser on line 4 due to a parse error.

Assigning a Value to a Variable

A variable is useless if you don’t assign data to it! Assigning data to a variable is done like so:

We now have a variable called $player_name that contains a string value of "Freddy".

Printing Variables

We can print out a variable’s value using echo.

If you want to combine a variable with a static string, you can use a period (.) to append your strings together, like so:

Alternatively, you can use quotes, which parses the string for the variable.

Here are a few more examples of printing out variables, just to hammer in the concept.

About PHP Data Types

In most programming languages, the data type of a variable can only be defined once. In PHP, this is not the case. If you are working with PHP, you can’t define the type of a variable. It’s defined implicitly, which means that the data type will automatically be set for you depending on the type of data you assign the variable. This might sound confusing now, but later on, it will make sense, so just bear with me.

Null Data Type

The data type null refers to "nothing". Every variable that has no value assigned to it will be a variable of the type null. Null is exactly 0 bytes. Assigning null to a variable will delete the contents of that variable from memory.

Data Type Switching

Did you see what we just did up there? We jumped from a null data type to a string data type and then, all of a sudden, the variable was null again. No magic or hocus pocus involved, promise!

PHP is loosely typed, which means a variable is not restricted to just one data type. This means that you’re allowed to switch any variable between all the available data types without having to do anything. This is also referred to as type juggling.

However, I must note that type switching is expensive in resources — and can introduce potential points of logic errors in your scripts — and thus you should always try to keep your variables restricted to one data type if possible.

Use type juggling only when you really need to.

Bool Data Type

Bool is short for Boolean. It’s the smallest data type. A Boolean can only be one of two values: true or false.

About var_dump()

It’s time to talk about the var_dump() PHP function for a second, as it will help you greatly in debugging and learning more about your variables. This function shows you details about your variables, including what the contents of your variables are.

var_dump() is a function that will accept any expression. After processing the expression(s), the outcome and additional information about the result of the expression will be printed on the screen.

To keep things readable, it’s a good idea to always wrap a call to var_dump() between the HTML tag. This is not needed, but something that does improve readability of the output.

Tip: Passing multiple parameters to a function is done by separating them with a comma (,).

The following image shows a screenshot of the output of var_dump(). Notice that it tells you the data type, the size and the value of both variables. For example, $has_permission = 'false'; results in a var_dump of string(5) "false", which means that it is a string data type, that there are 5 characters, and that the string value is ‘false’.

Just like we expected.

As you can see, var_dump() is a very useful function. In the context of this PHP guide, it serves perfectly well to find out how type juggling works — but you’ll find it to be a great tool for debugging your PHP scripts.

Int Data Type

An int, which is short for integer, is simply a number. The maximum size of an integer is platform-dependent (meaning it depends on your web server’s operating system and settings), although a maximum value of about 2 billion is typical. If the server is a 64-bit platform, the maximum value is around 9e18.

Integers are always used to store numeric values. Because they are numeric, you can perform mathematical operations on them.

Float Data Type

Unlike integers, which have to be whole numbers, floating points can have decimals such as 12.3 or 6051.32179.

Examine and test the following code block to see how float variables work:

Our integer switched to a float data type by dividing it by 6.

A float has more precision than an integer but requires more storage space than an integer. The maximum size of a float is (just like an integer) platform-dependent. The maximum value is typically 1.8e308.

Floating Point Imprecision

The binary system (i.e. 1’s and 0’s), was not build for floating point numbers. That’s why simple decimal fractions like 0.4 and 0.8 cannot be converted to their binary counterparts without a small loss of precision. Keep this in mind when you are developing a web application that has to deal with a lot of floating point numbers.

String Data Type

If there’s one data type that you should already be familiar with, it’s the string because you’ve already seen it in action earlier. The string data type is the biggest data type PHP knows. The maximum size equals the size of the server’s memory. You should always take care that this size should not be exceeded (which is hard to do unless you’re intentionally trying to exceed it — but still, you should watch out).

We already covered combining regular text strings with variables and you also know what the difference is between using an apsotrophe (e.g. ’string’) versus a quote (e.g. "string"), which was covered in the Learning PHP: Get Started Using PHP guide.

What we haven’t talked about are escaped characters. Remember how we took care of our indentation with \n and \t in the "Getting Started" guide? These are called linefeeds and they are categorized as escaped characters.

Read, analyze, and test the following code block to understand escaped characters in string variables. Also, check out this table to see a list of escaped characters in PHP.

Conclusion

In this guide, we learned as much as possible about commenting your code, variables, variable types and variable casting. If you have any questions, feel free to pose them in the comments.

Related Content

About the Author

Elias Zerrouq is a young web developer located in the Netherlands. He specializes in back-end development (PHP and MySQL) and classifies himself as a non-designing web developer (front-end development is okay though). Contact information can be found through his personal website.




More...