Home Blog Variable Variables in PHP

Variable Variables in PHP

0
Variable Variables in PHP

Variable variables are just variables whose names can be programmatically set and accessed.  For example, the code below creates a variable called $hello and outputs the string “world”.  The double dollar sign declares that the value of $a should be used as the name of a newly defined variable.

<?php
$a = 'hello';
$$a = 'world'
echo $hello;
?>

 

Output: world

It is one of the biggest time-savers in PHP is the ability to use variable variables.  While often intimidating for newcomers to PHP, variable variables are extremely powerful once you get the hang of them.

Example

<?php
$x = "100";
$$x = 200;
echo $x."<br/>";
echo $$x."<br/>";
echo "$100";
?>

Output:

100
200
200

In the above example

You first assign the value of a variable, ($x) as the name of another variable. When you set $x to a value, it will replace that variable name with the value of the variable you provide.
variable $x hold value = 100.

$$x hold value = 200. now we want to print the value.
echo $x gives output:100
echo $$x gives output:200.
echo $100 gives value.200. because it also acts as a reference variable for value = 200.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here