Now that we know how to assign values to variables, let’s move on to more interesting things, namely making those values work for us in expressions and calculations. PHP makes use of the standard mathematical operators, addition (+), subtraction (-), multiplication (*) and division (/) inside expressions, or calculations to assign values to variables based on the result.
Expressions using operations are written just like you’d write them down on paper, with two values or expressions either side of each operator, and in the case of an expression using more than one operator, precedence is decided by either using brackets, or through the rules of precedence associated with mathematical operators
$a = 3+5; //$a is assigned the value 8
$b = $a-7; //$b becomes 1, since $a represents 8 here
$c = 6+4*5 //$c becomes 26 (* takes precedence, see paragraph below)
$d = 5/3 //$d becomes 1.6667, a floating point value
In line 3 here, we see the rules of operator precedence at work. Multiplication has a stronger precedence than addition, so the expression “4*5″ is evaluated first, to produce 20. The equivalent expression becomes 6+20. If we wanted to have things otherwise, we can use brackets to force precedence to our liking.
$c = (6+4)*5 //$c becomes 50
the rules of precedence state that * and / have stronger precedence than + or -, although we can run into more complex situations depending on how we choose to frame our expressions, even when we’re only using one operator
$a = 3 - 4 - 5; //equals -6
$b = 3 - (4 - 5); //equals 4
The full range of operator precendece (which includes logical operators and more) is outside the scope of this tutorial, but it’s something to be constantly vigilant for when writing expressions, to ensure that your values come out the way you’d expect;
In an earlier tutorial, I showed you how to output short lines of text to screen using the “echo” statement. The same can be done with variables
A useful function to keep in mind is var_dump(), which can be used to display useful information about a variable
$c = "Hello world";
var_dump($c);
$c = 5/3;
var_dump($c);
Which produces the output
string(11) "Hello world"
float(1.6666666666667)
This tells us that $c initially contains a string with 11 characters. After the division operation, it then contains a floating point value, with the actual value contained in brackets. The function var_dump becomes especially useful when working with arrays
As a side note here, this is something that raises the fact that PHP is a weakly typed language. This means that there is no strict rule about e.g. changing the type of data a variable holds, or applying operations that add an integer
and a string
, e.g. the operation
2 + "2"
Will give us
4
PHP interprets the string "2"
as a number in this context, and converts it to an integer.
This is something to bear in mind when working with data in PHP. In some edge cases, you can get strange and unexpected results from operations.
Constants are a special type of datatype in PHP which, as their name might suggest, remain constant throughout the execution of an application. Constants can be accessed from anywhere within the code, regardless of scope, and this combined with their unchanging nature, makes them a good choice for application-wide settings.
Constants are initialised via the use of the define() function, and can only represent scalar values (i.e. constants cannot represent arrays or other complex data types)
Here is an example of a constant definition, and usage
define ("MYCONSTANT", 500);
echo MYCONSTANT;
The above code will produce the output
500
Constants have to adhere to the same naming conventions as standard variables – an underscore or letter followed by any number of letters, underscores or numbers, and although they can use both uppercase and lowercase lettering, traditionally they are only ever used with upper-case letters, and rarely contain numbers.
A useful function to use if you wish to recall the value of a constant dynamically (i.e. you need to retrieve a value based on the contents of a variable at runtime) is the constant() function. Here is an example of its usage
$name = "MYCONSTANT";
define ("MYCONSTANT", 500);
echo constant($name);
Again, this will output
500
PHP provides a number of predefined variables for use in scripts which can be used to gain access to a range of information about the server and filesystem, as well as information about the visitor. For example, the variable $_SERVER contains information about the visitor’s browser and operating system (although nothing which will dramatically impact upon privacy)
echo $_SERVER['HTTP_USER_AGENT'];
Will output
Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Which informs you that I’m using an operating system identifying itself as “Windows NT 6.0″ (actually Vista, but that’s how it reports itself) as well as using the latest version of the Firefox browser.
Other useful information can be gained through the $_SESSION variable, which provides secure information about the current user, and can be used to manage secure login systems and $_COOKIE, which allows you to track user activity between website visits. If you’ve ever ticked a box on a login screen which asks you “Do you want this site to remember you?”, then that will most likely be using the $_COOKIE variable.
Also available are user submitted values through the $_GET and $_POST variables, which are essential for processing forms and other information passed from the user to the server. You’ve most likely used forms to submit this sort of information yourself and not even been aware of it – when entering your email address into websites, logging in to secure areas or buying items online and entering your personal details.
A later tutorial will cover everything you need to know about the $_GET and $_POST variables to construct your own interactive web application
There are two ways to retrieve the value of a variable, they are called by value and by reference. If you imagine a variable as a box containing a particular number, or a particular string, then the way we’ve been accessing this box so far is by looking at what the box contains, and making a new copy of the box every time we wish to assign the value to a new variable.
Take the following code
$a = 10;
$b = $a;
$a = 20;
echo "b = ",$b;
This will produce the fairly obvious output
b = 10
Lets look a little deeper into what’s actually happening here though. In line 2 of the above code, we’re assigning the variable $b to be equal to the value held in the variable $a. In line 4, we print this value. Even though the value of $a has changed in line 3, this doesn’t affect the value held in $b, since we’ve already told PHP to assign $b the value of 10. Now, let’s make a little adjustment..
$a = 10;
$b = &$a; //so, $b = 10 again, right?
$a = 20;
echo "b = ",$b; //nope! $b = 20
The only change here is an adjustment to the assignment expression in line 2. There is now a new symbol preceding $a, an ampersand. In PHP, this is used to say that, instead of using the value of $a, we are using the location of $a instead. Here, the important thing to consider is that $b is not assigned to the value of $a but instead to whatever $a contains at any given point of time.
Effectively, we have not created a new copy of a variable, but have simply assigned $b to equal whatever $a equals. And so, the output of the above code will be
b = 20
The process goes like this:
Variable variables aren’t quite as bewlidering as their name might suggest. Put simply, they are a way of changing the name of variables during program execution, so that multiple values can be accessed through only one line of code. Variable variables are used by preceding the variable name with another dollar sign ($). This new variable then takes, as its name, whatever the value of the original variable way. To make things clearer, here is an example
$bob = "Hi, my name is Bob";
$name = "bob";
echo $$name;
Which gives us
Hi, my name is Bob
Confusing intially, but this is functionally identical to the following
$bob = "Hi, my name is Bob";
$name = "bob";
echo $bob; // $$name = ${$name} = ${bob} = $bob
Here, on lines 1 and 2, we’re creating two variables, $name and $bob. On line 3, we’re using the “variable variable” $$name, which, in this example, will evaluate to the variable $bob (since $name=”bob”)
Variable variables can be very useful when you have a large number of variables and wish to dynamically modify them without the hassle of typing in each individually. It’s perhaps a little more complex than the beginner/intermediate scope of this tutorial, but later on, once you’ve mastered arrays and loops, you’ll begin to see how these can be of use
I hope that this has been an insightful tutorial, and has given you some guidance on the use of variables in PHP. This tutorial doesn’t cover everything, and aims only to provide a general overview of some of the more interesting aspects of variable use in PHP.
To get more information on variables, I suggest looking up the appropriate pages on PHP’s own documentation site, a great resource, and one I refer to often.
The following tutorials cover more complex ways of representing data in PHP, specifically covering the topic of arrays.
Robin is the dedicated developer behind Solarise.dev. With years of experience in web development, he's committed to delivering high-quality solutions and ensuring websites run smoothly. Always eager to learn and adapt to the ever-changing digital landscape, Robin believes in the power of collaboration and sharing knowledge. Outside of coding, he enjoys diving into tech news and exploring new tools in the industry.
If you'd like to get in touch to discuss a project, or if you'd just like to ask a question, fill in the form below.
Send me a message and I'll get back to you as soon as possible. Ask me about anything - web development, project proposals or just say hi!