phpforeachvariable-variables

Access a variable using a string value as it's name


I have this php code foreach loop inside another foreach what I need is to set all the array value one by one on each loop(red, blue, green, black). I need to change $green in

data-percent="<?php foreach ($green as $row) { echo $row->ink_numbers; }?>">

with all the value in array one by one on each loop I try:

 data-percent="<?php foreach ('$'.echo $value as $row) { echo $row->ink_numbers; }?>">

but it does not work. PLEASE HELP

COMPLETE CODE:

<?php
 $color  = array( 0 => 'red' , 1 => 'blue', 2 => 'green', 3 => 'black' );
 foreach ($color as $key => $value) {

?>


                                                                                    <!-- make $green dynamic -->
<div class="<?php echo $value; ?> progress-pie-chart" data-percent="<?php foreach ($green as $row) { echo $row->ink_numbers; }?>">
  <div class="ppc-progress">
    <div class="<?php echo $value; ?> ppc-progress-fill"></div>
  </div>
  <div class="<?php echo $value; ?> ppc-percents">
    <div class="pcc-percents-wrapper">
      <span>%</span>
    </div>
  </div>
</div>
<?php } ?>

Solution

  • You can use a variable name, like this:

    <?php foreach ($$value as $row) { echo $row->ink_numbers; }?>"
    

    So when $value = 'green' the foreach will loop through $green.