PHP Variables Tutorial
In this tutorial we learn how to create and use mutable temporary data containers in PHP, called variables.
Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)
Let's jump right in.
What is a variable?
When an application runs, it stores data temporarily in the system’s memory (RAM).
When the data is no longer used, or the application is terminated, the data is deleted and the memory is released back to the system.
A variable is a data container that stores this type of temporary data.
How to declare a variable
A variable is declared by writing a dollar sign $ , immediately followed by the variable name. Finally, the command statement is terminated with a semicolon.
<?php $message; ?>
In the example above, we declared a variable called $message. Currently, it doesn’t store any data inside of it.
How to initialize a variable
When we declare a variable, we can immediately assign data to it. This is called variable initialization, and uses the assignment operator.
To initialize a variable, we declare the variable as we normally would, then write the assignment operator = and the value we want the variable to hold.
Finally, the command statement is terminated with a semicolon.
$variable_name = value;
<?php $message = "Hello World"; ?>
In the example above, we initialize a variable called $message with the string value “Hello World”. If we want to access the string, all we need to do is to refer to the variable name.
How to assign data to an empty variable
We can assign data to an empty variable, or change data in a variable with the same initialization syntax.
<?php // Empty variable $message; // Assign data to empty variable $message = "Hello World"; // Change data in a variable $message = "Hello there"; ?>
In the example above, we can see that the same initialization syntax is used to assign data to an empty variable, and change data in a variable that already has data assigned to it.
How to access data in a variable
We don’t need to refer to the specific memory address that the data is stored at, we can simply refer to the variable. The interpreter will do the rest.
<?php // Initialize variable $message = "Hello World"; // Access data echo $message; ?>
In the example above, we print the data stored inside the variable to the page by referring to it.
As we learned in the First Application: echo command statement tutorial lesson, the echo command statement is used to print data to the page.
When referring to a variable, we have to include the $ symbol otherwise the interpreter will think it’s a constant and raise an error.
Summary: Points to remember
- A variable in PHP is always prefixed with the $ symbol.
- A variable can be declared without a value, or initialized with a value directly.
- Data is assigned to, or changed, with initialization syntax.
- Data is accessed by simply referring to the variable.