3

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".

2
  • 3
    Don't do it. Just use an array. You will thank me later: $sampleVar[$row[1]] = 'a string'; Commented May 22, 2016 at 3:56
  • Not sure what you mean @AbraCadaver. My illustration and question was simply to find out if I could dynamically make up a variable, which (at)LucM helped me to achieve. My script and usage is way more complex than this simple example. Each of the $sampleVar99's are, in fact, arrays in and of themselves in my script. But for the very essence of my question, (at)LucM shows how to do it. Honestly, I was too deep in it and overthinking it. A fresh set of eyes from (at)LucM helped me to actually see the solution it so obviously. I appreciated his assistance. Commented May 22, 2016 at 11:13

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

6 Comments

Ah, no I did not. But I will now @LucM
It did not work. I get this error Notice: Undefined variable: sampleVar in
Of course, your variables sampleVar and $row[1] must be defined.
see my "more info" in my OQ if that helps to answer my question ... "can this actually be accomplished".
Thanks for the EDIT @LucM. i'll try that now.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.