PHP Variables Explained: Difference Between $message and $$message
What is $message in PHP?
The $message is a simple PHP variable. You can assign any value to it like text, numbers, or even arrays.
$message = "Hello World!";
echo $message;
Here, PHP will print:
Hello World!
So, $message is just a normal variable that stores a value.
What is $$message in PHP?
Now comes the tricky part. The $$message is called a variable variable in PHP. It means the value of $message will be used as the name of another variable.
Confused? Let’s see an example:
$message = "greeting";
$$message = "Hello World!";
echo $greeting;
In this case:
$messageholds the value"greeting".$$messagebecomes$greeting.$greetingis then assigned the value"Hello World!".
The output will be:
Hello World!
This is why $$message is known as a variable variable—it creates a new variable whose name comes from the value of another variable.
Key Difference Between $message and $$message
- $message → A regular variable that stores a value.
- $$message → A variable variable that uses the value of
$messageas another variable’s name.
In short:
$message = "greeting";
$$message = "Hello";
// Now $greeting = "Hello"
When Should You Use $$message?
To be honest, variable variables are not used very often in modern coding practices because they can make the code harder to read. However, they can be useful in some cases like:
- Dynamic variable naming
- Handling data with unknown variable names at runtime
But if you’re just starting with PHP, focus more on regular variables. You’ll hardly need $$message in daily coding.
Final Thoughts
The difference between $message and $$message lies in how they store values. One is a simple variable, while the other is a variable variable that creates new variables on the fly. Once I understood this, PHP became much less confusing for me.
Just remember: $message is straightforward, while $$message is like a “variable generator.”
