Double Dollar Or Variable Variables In PHP

Apart from the normal variables in PHP, which we write like $a, there is also a variable variable which is written like $$a.

The problem is when someone wants to search what does this double dollar mean, they do not know how to search. Well searching will be a lot easier if they search by variable variables in PHP, and the best resource as always is at php.net.

To give a short explanation here it is used to give variable / dynamic names to variables.

Lets see a quick example. Say a value increases by a fixed amount everyday of the week. To enter and output the value for each day the code can be like –

$dyn = array("Sunday","Monday","Tuesday","Wednesday","Thursday", "Friday","Saturday");
$i=0;
foreach($dyn as $eachDyn){
$$eachDyn = $i;
$i+=2;
}
foreach($dyn as $eachDyn){
echo $eachDyn ." = ".$$eachDyn;
}

If the fixed amount changes later we need to just change the line $i+=2; to maybe say $i+=5; and that would be sufficient. No need to change each day individually.

Leave a comment

Your email address will not be published. Required fields are marked *