I have the following variables:
question_0, question_1, question_2.
Is there a way to access those variable using string concatenation like this: question_(the expression to match all possible characters or numbers goes here)
? To be more specific, I have an array in the following format:
[{"question_0":{"question_id":"0","type":"multiple_choice_single","title":"ss"}},
{"question_4":{"question_id":4,"type":"multiple_choice_many","title":"ss"}}]
I would like to iterate over the array and access the question_(whatever)
.
foreach ($response["questions"] as $value): ?>
<tr>
<th><?=$value->question_->question_id?></th>
</tr>
<?php endforeach; ?>
my problem is that question_0, question_1 are not in incremental order like this: question_0,question_1,question_2. They are random numbers:question_0,question_4,question_8
You can access those properties with json_decode
:
<?php
...
foreach (json_decode($response["questions"], true) as $value): ?>
<tr> <th>
<?=reset($value)['question_id']?>
</th> </tr>
<?php endforeach; ?>
With reset()
you select the value of the first key, whatever it is (question_xx).
See it run on eval.in.
I think what you need is this:
<?php
$x1 = "X";
$x2 = "Y";
$x3 = "Z";
$x4 = "Q";
for($i=1; $i<5; $i++)
{
echo ${"x".$i};
}
?>
you can refer to variables as ${"x"};
, you can concatenate within those curly brackets.
also please try to format your question properly, a bad question will yield bad answers, you can tell by the comments how many struggled to understand your question.