Anthony Anthony - 2 months ago 11
PHP Question

How to appending variable to a variable name

I have a similar problem with this topic
Appending a value of a variable to a variable name?

but the answer not solve my problem,
i have variable,$item->ans_cont1 ..... to $item->ans_cont34
tried

for($i=1;$i<35;$i++) {
$inputval = 'item->ans_cont'.$i;
echo $$inputval; //output is empty
echo ${'item->ans_cont'.$i}; //output is empty
}


but not work,is it "->" arrow problem?how to fix it?

Thanks!

Answer

$item is an Object so you have to call its attribute:

$inputval = $item->{'ans_cont'.$i};
// Or 
$inputval = 'ans_cont'.$i;
echo $item->$inputval;
Comments