25

I have a loop that goes from 1 to 10 and prints values in

$entity_object->field_question_1 through 10 so...

$entity_object->field_question_1, $entity_object->field_question_2, etc

And I want to print this in this loop, how can I get the variable? I tried doing the

$var = "entity_object->field_question_".$i;
print $$var;

But that did not work...

How can I get these values?

4 Answers 4

48

This should work:

$var="field_question_$i";
$entity_object->$var;
Sign up to request clarification or add additional context in comments.

Comments

23

Actually you need to take the variable outside the string like this in order to those solutions to work: $var="field_question_".$i;

$entity_object->$var;

Or

$entity_object->{"field_question_".$i}

Comments

10

First of all, arrays are more suitable for what you want to do.

The answer to you question: print $entity_object->{"field_question_$i"};

Comments

0

Or you can typecast between arrays and objects.

Array's are simple in the fact that they are organized and easily accessed. Objects are quite the differ but off many pro's.

Set your objects like so:

$entity_object["field_question_{$i}"] = ''//value;

They can then be typecasted to an object:

$entity_object = (object)$entity_object;

You would then reference them like:

$entity_object->field_question_1 ...;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.