0

I'm creating some variable names dynamically in a while loop:

while($count < $agendaItemsCount) {
      $tr_mcs_agendaitem_[$count]_1 = get_post_meta( $post->ID, '_tr_mcs_agendaitem_' . $count . '_1', true );
    ++ $count
}

But this code is causing an unexpected string parse error. How do I write this code so that the new var gets declared with the count variable output along with the rest of the var name?

Mike Rifgin
  • 10,409
  • 21
  • 75
  • 111
  • 3
    What's the good reason for not using a key-value pair in an array? – Incognito Feb 20 '12 at 14:01
  • possible duplicate of [PHP Variable Variables](http://stackoverflow.com/questions/4511948/php-variable-variables) – jprofitt Feb 20 '12 at 14:03
  • @Incognito I have no control of the data coming back...i'm working in wordpress. Curly braces do not work....$tr_agendaitem_{$count}_1 = get_post_meta( $post->ID, 'agendaitem_' . $count . '_1', true ); still produces a syntax error – Mike Rifgin Feb 20 '12 at 14:09
  • 2
    @elduderino That's the perfect case for using a map of key-value pairs. The 'custom name' would be the key, and the data would be the same data. This is how PHP handles GET/POST results, since for those the variable's name won't be known beforehand. – Kitsune Feb 20 '12 at 14:13
  • I'm not following you. Can you give me an example of what you mean? – Mike Rifgin Feb 20 '12 at 14:18

1 Answers1

2

So you want to create variables like $tr_mcs_agendaitem_1_1, $tr_mcs_agendaitem_2_1 etc? While I advise using an array, you can do the following:

$collection = array();
while($count < $agendaItemsCount) {
  $collection['tr_mcs_agendaitem_'.$count.'_1'] = 
       get_post_meta( $post->ID, '_tr_mcs_agendaitem_' . $count . '_1', true );
    ++ $count;
}
extract($collection);

Another solution would be to use "variable variables":

while($count < $agendaItemsCount) {
  $varname = 'tr_mcs_agendaitem_'.$count.'_1';
  $$varname = get_post_meta( $post->ID, '_tr_mcs_agendaitem_' . $count . '_1', true );
  ++ $count;
}
chiborg
  • 26,978
  • 14
  • 97
  • 115
  • Don't forget to initialize the array: `$collection = new array();`, in case $agendaItemsCount is 0. – binar Feb 20 '12 at 16:32