简体   繁体   中英

variables in variable names

If this title is bad sorry, but i don't have any idea to set it better.

I use a cms which has extra fields, i created 3 extrafields with labels: box_title_1, box_title_2, box_title_3

If want to get his values with a for loop, but the php can't check what i need, my php code is:

for($i=1; $i<=3; $i++) {
     echo $this->element->box_title_ . $i;
}

Values what i get from my loop are only number (1,2,3) If i call it direct $this->element->box_title_1 then i see value, but i want to dynamic it, possible?

@m_73, you can use this notation:

for($i=1; $i<=3; $i++) {
     echo $this->element->{"box_title_" . $i};
}

Hope this helps.

The link that @Niet posted has the information.

Here is a quick example to get you going

$type='last';
${"name_$type"}='johnson';

echo 'variable "$name_last" = '.$name_last;

this will output

variable "$name_last" = johnson

perhaps the quickest way, maybe not the most secure, is to use eval

for($i=1; $i<=3; $i++) {
     echo eval("$this->element->box_title_$i;");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM