0

How can I build a composed variable while creating a variable in PHP? (Sorry I'm not sure how to call the different elements)

This is what I'm trying to do:

$language = 'name_'.$this->session->userdata('site_lang');

for ($i=1;$i<=3;$i++) {
    $data = $arraydata->$language_.$i; // problem is here
}

I would like $language_.$i to be equivalent to name_english_1, next loop name_english_2... The same way I built $language

2
  • don't generate dynamic variable names. that's just bad coding. use an array. $arraydata->$language[$i] is FAR easier to maintain/understand. Commented Apr 29, 2016 at 20:58
  • but the fields in my database are called ´name_english_1´, ´name_english_2´ so how could I retrieve them? Commented Apr 29, 2016 at 21:01

2 Answers 2

3

If you want to use an expression in a computed property, you have to put the expression in braces. Also, you need to put the underscore in quotes.

$data = $arraydata->{$language."_".$i};

However, I suggest you redesign your data structure. Instead of having separate name_LANG_i properties, make a single name property whose value is a multi-dimensional array.

$lang = $this->session->userdata('site_lang');

for ($i=1;$i<=3;$i++) {
    $data = $arraydata->name[$lang][$i];
    // do something with $data
}

Whenever you find yourself using variable variables or variable properties, it's almost always a sign that you should be using an array instead.

Sign up to request clarification or add additional context in comments.

Comments

0

First construct the field name and then use it for accessing the field value from the object $arraydata. So your code should be like this:

$language = 'name_'.$this->session->userdata('site_lang');
for ($i = 1; $i <= 3; $i++) {
    $var = "{$language}_{$i}";
    $data = $arraydata->$var;

    // echo $data;

}

Comments

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.