H. Ferrence H. Ferrence - 6 months ago 15
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
$row[1]
will, in fact be either "
01
", or "
02
", or "
03
", or "
04
".

Answer

What you are looking for is called variable variables

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

EDIT

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

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