A variable is used in PHP scripts to represent a value. As the name variable suggests, the value of a variable can change (or vary) throughout the program. Variables are one of the features that distinguish a programming language like PHP from markup languages such as HTML. Variables allow you write your code in a generic manner. To highlight this, consider a web form which asks users to input their name and favorite color.Every time the form is completed, the data will be different. One user may say his name is John and his favorite color is blue. Another may say her name is Susan and her favorite color is yellow. We need a way of working with the values a user enters. The way to do this is by using variables. There are a few standard variables that PHP creates automatically, but most of the time variables are created (or declared) by you, the programmer. By creating two variables called
$color, you could create generic code which can handle any input values. For John, this code:
echo "Hello, $name. Your favorite color is $color.";
Hello, John. Your favorite color is blue.On the other hand, Susan would see:
Hello, Susan. Your favorite color is yellow.We will look into variable names and displaying the value of variables in the rest of this article, but the important point now is to understand how the use of generic variables can make processing data easy.
Creating VariablesIn PHP, simply writing the name of a variable for the first time in a script will create it. There’s nothing extra you need to do. The variable name has to follow some standard rules, though:
- The name starts with a
- The first character after the
$must be a letter or underscore
- All subsequent characters can be a combination of letters, numbers and underscores
$customerName is a valid variable name because it observes all three rules above.
$123customer is not valid because it violates the second rule, the first character after the
$ sign must be a letter or underscore.
It’s a good idea to give your variable a meaningful name. If the data you will be storing is a customer’s name, a sensible name might be
$customerName. You could also call it
$abc123, but I hope you agree that the former suggestion is better.
There are different conventions you can follow when writing variable names. Regardless of what you choose, it is important to be consistent and follow the convention throughout your script. For example, you can use an underscore to separate words (e.g.
$customer_name), or use capital letters to differentiate words, a style called Camel Case (e.g.
You are allowed to use both upper and lower case letters when naming a variable, but be aware that
$CustomerName is not the same as
$customerName. PHP will treat the two as different variables! This reinforces the need to stick to a naming convention.
Assigning VariablesNow that you know you can have PHP create a new variable anytime you need it just by writing a new name, let’s look at another example to learn about assigning values to them.
First, the variable
$customerName = "Fred";
$customerID = 346646;
$customerName = $customerID;
$customerName is given the value “Fred”. This is referred to as assigning a value. And because this is the first time
$customerName is used, the variable is created automatically. Anytime you write
$customerName after that, PHP will know to use the value “Fred” instead.
$customerID is written. A variable can be created without assigning a value to it, though this is generally not considered to be good practice. It is better to assign a default value just so you know it has a value. Remember, variables are variable, so you can always change the value later. Afterwards, the variable
$customerID is assigned the value 346646.
Finally, the value of
$customerID is assigned to
$customerName. You can assign the value of one variable to another; in this case the value of
$customerID (346646) overwrites the value in
$customerName (“Fred”) so that both variables now represent 346646!
Notice how the types of data referenced by a variable have different “types.” This property is called the data’s data type. “Fred” is given with quotation marks, so it is a string (string is just a fancy name for text). 346646 is obviously a number (more specifically, an integer).
Here are some examples of assigning values with different data types:
Now that you understand the basics of naming variables and assigning values, let’s look at this example and see if you can work out the answer:
$total = 0; // Integer
$total = "Year to Date"; // String
$total = true; // Boolean
$total = 100.25; // Double
$total = array(250, 300, 325, 475); // Array
The examples in the previous section showed that values to the right of the
$firstNumber = 4;
$secondNumber = 6;
$result = $firstNumber + $secondNumber;
= sign are assigned to the variable name on the left of the
= sign, so the value 4 is assigned to
Have a close look at the last line. Though I haven’t explained it previously, the
+ sign is an operator, in this case performing addition. So what do you think the value will be in
If your answer is 10 then well done, that’s correct! If not, have a look at the example again and read the explanation carefully.
Displaying the Value of VariablesAs you saw at the beginning, you can display the value represented by a variable using
echo. You can also use
print if you’d like, as there is little difference between the two at this point besides less typing with
Perhaps you would like to make the example more meaningful by adding some text in quotation marks before the variable contents:
The dot between the text in quotation marks and the variable name is the concatenation operator. It joins the string and the value of the variable together.
You could avoid using concatenation and make use of interpolation instead. Interpolation is when the variable name appears in a string and is replaced by its value instead. Taking advantage of this can sometimes make your code easier to read.
echo "Customer name = " . $customerName;
PHP automatically performs interpolation on strings that are enclosed by double-quotation marks. If you wish to display the name of the variable with your text, you can use a backslash immediately before the variable name:
echo "Customer name = $customerName";
Alternatively, PHP will not perform interpolation on strings that are enclosed by single-quotation marks. So this is an equally effective statement:
echo "$customerName has the value: $customerName";
For more information about variables, check out the PHP documentation. You’ll review everything you’ve learned here, and learn about what special variables PHP will automatically define and make available to your scripts, how a variable is bound to the context in which it was declared, and even how variables can be used as the names for other variables!
Image via Kachan Eduard / Shutterstock
echo '$customerName has the value: ' . $customerName;
Frequently Asked Questions (FAQs) about PHP Variables
What is the significance of variable naming conventions in PHP?
Variable naming conventions in PHP are crucial for maintaining clean, understandable, and efficient code. In PHP, a variable starts with the $ sign, followed by the name of the variable. The variable name must begin with a letter or the underscore character. It can’t start with a number and can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). Variable names are case-sensitive ($age and $AGE are two different variables). Following these conventions ensures that your code is easily readable and less prone to errors.
How do PHP variables handle data types?
PHP is a loosely typed language, which means you don’t have to declare the data type of a variable when you create one. PHP automatically converts the variable to the correct data type, depending on its value. For instance, if you assign an integer value to a variable, PHP treats it as an integer. If you later assign a string to the same variable, PHP will treat it as a string.
What is the scope of a variable in PHP?
The scope of a variable is the part of the script where the variable can be referenced or used. In PHP, variables can be declared anywhere in the script. The scope can be local, global, or static. Global variables are accessible anywhere in the script, while local variables are only accessible within the function they are declared. Static variables retain their value even after the function execution is completed.
How can I use PHP variables with HTML?
PHP variables can be used within HTML code to dynamically generate web content. This is done by embedding PHP code within HTML. The PHP code is enclosed within special start and end processing instructions that allow you to jump into and out of “PHP mode.”
What are PHP variable variables?
A variable variable takes the value of a variable and treats that as the name of a variable. In other words, a variable variable allows us to change the name of a variable dynamically. This can be useful in certain situations, but it can also make code more complex and harder to understand, so it should be used sparingly.
How do I unset or delete a PHP variable?
You can unset or delete a PHP variable using the unset() function. This function destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.
How do I declare a global variable in PHP?
In PHP, global variables must be declared global inside a function if they are going to be used in that function. You can do this using the global keyword before the variable inside the function.
What are superglobals in PHP?
Superglobals in PHP are built-in variables that are always available in all scopes. This means that they can be accessed from any function, class, or file without having to do anything special. Some of the many superglobals in PHP include $GLOBALS, $_SERVER, $_REQUEST, $_POST, $_GET, $_FILES, $_ENV, $_COOKIE, and $_SESSION.
How do I convert a string into a variable name in PHP?
In PHP, you can convert a string into a variable name using variable variables. By placing a dollar sign ($) before a variable that contains a string, PHP will treat the string as a variable name.