PHP allows developers to reference variables dynamically. Take the following:

$myValue = "medal";
$medal = "Gold";
echo $myValue;
//outputs "medal"
echo $$myValue;
//outouts "Gold"

The $myValue echos “medal” as normal. But when using the $$ double dollar prefix it outputs “Gold”. This is the value of the $medal variable.

Dynamic variables like this can be very useful. Take a use case where you query a database using SELECT * and expect a series of values ‘item1’, ‘item2’, ‘item3’, ‘item4’ etc (possibly not the best database design but there you go).

To retrieve these values we could use:

      $checkVar = "item".$i;
        	echo $$checkVar;

In the above $$checkVar is evaluated from ‘item’ plus the loop value for $i ie ‘item1’, ‘item2’, ‘item3’ etc.

Creating Variable Named Variables

If you need to create dynamic variable names yourself, use the following double brackets syntax:

${'item'.1} = "Gold";

… which of course could be looped as in the following example:

$i = 1;
		$key = "value".$i;
		${'item'.$i} = $_POST[$key];
	}while($i <= count($_POST));

This snippet loops around a $_POST superglobal from a HTML form which has a number of fields ‘value1’, ‘value2’ ‘value3’ etc. The exact number can be unknown as the loop will keep looking until all the values have been retrieved.

This trick would tie in nicely with the Adding Form Fields Dynamically with jQuery tip where the user decides how many fields to add to the form.

Dynamic Variables and PDO Objects

Another quick thought on this. In a recent project I needed to loop a mySQL database where the field names were incremental ie item1, item2, item3 etc to item8 – as mentioned above. The data was been outputted via a PDO object. To make the code less repetitive the following trick was used:

for($i=1; $i<=8; $i++){
  $dValue = "item".$i;
  $dbValue = $row->{$dValue};

This trick uses the { } curly braces to evaluate the variable before passing it to the object.

Leave a Comment