H. Ferrence H. Ferrence - 1 year ago 72
MySQL Question

How to dynamically define a variable in PHP

Is there a way to name or define a variable based on the value of another variable?

I have a MySQL result set in $row[1].

I am trying to dynamically name a variable by appended the beginning of a variable with the value of $row[1] as follows:

$sampleVar.$row[1] = 'a string';

But get this error:
Fatal error: Only variables can be passed by reference in...

More Info:

I have these variables predefined:

$sampleVar01 = '';
$sampleVar02 = '';
$sampleVar03 = '';
$sampleVar04 = '';

The result of
will, in fact be either "
", or "
", or "
", or "

Answer Source

What you are looking for is called variable variables

$var = $sampleVar.$row[1]
$$var = 'a string';


After your edit, here's what you need to do:

$var = 'sampleVar' . $row[1];
$$var = 'a string';
echo $sampleVar01;