PHP Variables
Like most programming languages, PHP lets you create variables in your scripts. A variable is a storage container that holds a value. This value can change as the script runs. You can:
- Assign any value you like to a variable
- Access the value stored in a variable, and
- Change a variable’s value at any time.
Variables are useful because they let you write flexible scripts. For example, a script that can only add 3 and 4 together isn’t very useful. A script that can add any two values together, though, is much more flexible.
Creating a variable
To create a new variable in PHP, you can just write the variable’s name:
$myVariable;
Notice the dollar ($
) symbol before the variable name. All PHP variables have a dollar symbol in front.
This is known as declaring a variable. It’s also a good idea to give the variable an initial value at the time you declare it — this is known as initializing the variable:
$myVariable = 23;
If you don’t initialize a new variable then it takes on a value of null
.
Changing a variable’s value
You’ve just seen how to assign a value to a variable: you simply write the variable name, followed by an equals sign, followed by the value you want to assign.
To change a variable’s value, simply assign the new value:
$myVariable = 23;
$myVariable = 45;
$myVariable = "hello";
The first line of code creates a new variable with a numeric value of 23, while the second line changes the variable’s value to 45. The third line changes the value again — this time to a string of text, “hello”.PHP is a loosely-typed language, which means you can change the type of data that a variable holds whenever you like. In the above example, $myVariable
starts off holding a number, and finishes by holding a string of text.
Using a variable’s value
To use the value of a variable in your script, simply write the variable’s name. For example, to display the value of $myVariable
you’d use:
echo $myVariable;
To add the values of two variables $x
and $y
together and display the result, you could write:
echo $x + $y;
Variable names in PHP
Before leaving the topic of PHP variables, it’s worth taking a look at how to name variables. All PHP variable names have to follow these rules:
- They start with a
$
(dollar) symbol. - The first character after the dollar must be either a letter or a
_
(underscore) symbol. - The other characters may be letters, numbers, and/or underscores.
Variable names can be as long as you like, but it’s a good idea to keep them relatively short (otherwise they can get quite unwieldy). It’s also good to use meaningful variable names — for example, $numWidgets
is much more useful than $nw
.
PHP variable names are case-sensitive, which means that $myVariable
and $MyVariable
refer to different variables.
Now that you know how PHP variables work, you’re well on your way to writing useful PHP scripts!