php Increment name of variable in a loop

2019-08-03 13:19发布

问题:

I thought of a while loop but cant find the way around this:

$foo1 = get_post_meta( $post->ID, '_item1', true );
if (!empty($foo1)){
    echo  ("<div class='$foo1'></div>"); 
}

$foo2 = get_post_meta( $post->ID, '_item2', true );
if (!empty($foo2)){
    echo  ("<div class='$foo2'></div>"); 
}

And so on... for a hundred times until I reach $foo100 and _item100 Any idea to achieve this to not repeat these 4 lines over and over?

回答1:

You don't need variable variables for that, but just a for loop like this:

for( $i=1; $i<101; $i++ ) {
  $klass = get_post_meta( $post->ID, '_item' . $i, true );
  if( !empty($klass) ) {
     echo "<div class='$klass'></div>"; 
  }
}

This works as long as you do not need the $fooX variables later on. If you need them, you would have to use either mentioned variable variables or an array to collect all the values.



回答2:

you're thinking well at a while loop

You could use:

   $counter = 1;
   while ($counter< 100) // or whatever limit you have
   {
       $foo = get_post_meta( $post->ID, '_item' . $counter , true );
         if (!empty($foo)){
           echo  ("<div class='$foo' . $counter .' ></div>"); 
              }
     $counter++;
    } 

If you copy this code you're probably get into some compiling errors because of the string concatenation.

Basically you need to concatenate "_item" string with your current $counter.

Here are some string concatenation examples.

Let me know if you have any questions.