Thanks for the help below, however, I’m still having some problems, I’ll try and explain further:
I have a variable as follows:
$value['questions'];
Now, I need to do a check in a loop, so I have this piece of code in the loop:
if($results[$value['questions']]==4){blah blah blah};
but the problem I am having is that the value of $value['questions'] is q1 but I need the q1 to be a string (i.e. inside quotes '') in the $results section of the code, so the $results element should look like this…
if($results['q1']==4){blah blah blah};
currently it looks like this
if($results[q1]==4){blah blah blah};
Make sense?
Thanks again for the help.
Hi all,
I hope there is a simple solution!
I have a variable:
$results['q1'];
Is it possible to have the ‘q1’ element as a variable, something like this:
$results['$i[question]'];
Have not been able to find a solution on Google and researching the PHP manuals…
Anyone got a suggestion/ solution?
Thanks,
Homer.
Yes, it is possible to use a variable as indice, when accessing an array element.
As an example, consider this portion of code :
Which will give the following output :
Here,
$indiceis a quite simple variable, but you could have used whatever you wanted between the[and], like, for instance :$results[ my_function($parameter) ]$result[ $my_array['indice'] ]$result[ $obj->data ]Basically, you can use pretty much whatever you want there — as long as it evaluates to a scalar value (i.e. a single integer, string)
In your specific case, you could have
$resultsdeclared a bit like this :And
$iwould be declared this way :Which means that
$i['question']would be'q1', and that the following portion of code :Would get you this output :
Edit : To answer the specific words you used in the title of your question, you could also use what’s called variable variable in PHP :
Here :
$indiceis'variable'$$indiceis'a'And, of course, don’t forget to read the Arrays section of the PHP manual.
The Why is $foo[bar] wrong? paragraph could be of interest, especially, considering the example you firt posted.
Edit after the edit of the OP :
If
$value['questions']is'q1', then, the two following portions of code :and
should do exactly the same thing : with
$results[$value['questions']], the$value['questions']part will be evaluated (to'q1') before the rest of the expression, and that one will be the same as$results['q1'].As an example, the following portion of code :
Outputs
4.