Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Difference between the and$ operator in php
In PHP, $ and $$ are both used with variables but serve different purposes. $ is the standard variable prefix, while $$ creates a variable variable − a variable whose name is stored in another variable.
$ (Variable Operator)
The $ operator is used to declare and access variables in PHP. Every variable in PHP starts with a dollar sign followed by the variable name. Variables can hold any type of value including integers, strings, arrays, and objects.
$name = "Alice"; // string variable $age = 25; // integer variable echo $name; // outputs: Alice
$$ (Variable Variable Operator)
$$ is a special operator that creates a variable variable. It takes the value of one variable and uses it as the name of another variable. This allows you to dynamically reference variables at runtime.
$varName = "greeting"; $$varName = "Hello!"; // creates $greeting = "Hello!" echo $greeting; // outputs: Hello!
How It Works
$welcome = "message"; // $welcome holds the string "message"
$message = "Welcome to TutorialsPoint";
echo $welcome; // outputs: message (value of $welcome)
echo $$welcome; // outputs: Welcome to TutorialsPoint
// $$welcome ? $"message" ? $message
Key Differences
| Feature | $ (Variable) | $$ (Variable Variable) |
|---|---|---|
| Purpose | Declares and accesses a variable | Uses value of one variable as the name of another |
| Name Known At | Compile time (static) | Runtime (dynamic) |
$x = "hello" |
$x → "hello" |
$$x → value of $hello
|
Example
The following example demonstrates both $ and $$ ?
<?php
$welcome = "message";
$message = "Welcome to TutorialsPoint";
// $ accesses the variable directly
echo '$welcome = ' . $welcome;
echo "
";
// $$ uses the VALUE of $welcome ("message")
// as a variable NAME, so $$welcome = $message
echo '$$welcome = ' . $$welcome;
echo "
";
// Another example: dynamic variable creation
$color = "red";
$$color = "#FF0000"; // creates $red = "#FF0000"
echo '$red = ' . $red;
echo "
";
// Chain example
$a = "b";
$b = "c";
$c = "Hello from variable variable!";
echo '$$$a = ' . $$$a; // $$$a ? $$b ? $c
?>
The output of the above code is ?
$welcome = message $$welcome = Welcome to TutorialsPoint $red = #FF0000 $$$a = Hello from variable variable!
Conclusion
$ is the standard way to declare and access variables in PHP. $$ creates variable variables by using one variable's value as another variable's name, enabling dynamic variable references at runtime. While powerful, variable variables should be used sparingly as they can make code harder to read and debug.
