2

I have 30 variables to show, but write the code 30 times is not smart. how can I improve this code? Thank you!!

<?php if ($dimension_01_label) { ?> 
  <tr>
     <td><?= $dimension_01_label ?></td>
     <td><?= $dimension_01 ?></td>
  </tr>
<?php }; ?>
<?php if ($dimension_02_label) { ?> 
  <tr>
    <td><?= $dimension_02_label ?></td>
    <td><?= $dimension_02 ?></td>
  </tr>
<?php }; ?>
<?php if ($dimension_03_label) { ?> 
  <tr>
    <td><?= $dimension_03_label ?></td>
    <td><?= $dimension_03 ?></td>
  </tr>
<?php }; ?>
Jeff Monteiro
  • 721
  • 1
  • 7
  • 17

5 Answers5

1

You could use two things:

  1. Use arrays and iterate throug it
  2. Use dynamic variables via {} Examples here: Dynamic variable names in PHP
Community
  • 1
  • 1
bish
  • 3,381
  • 9
  • 48
  • 69
0

You can use variable of variable -

for($i = 1; $i <=30; $i++) {
    $var1 = "dimension_".str_pad($i, 2, 0, STR_PAD_LEFT)."_label";
    $var2 = "dimension_".str_pad($i, 2, 0, STR_PAD_LEFT);
    if ($$var1) {
       echo "<td>".$$var1."</td><td>".$$var2."</td>";
    }
}

Chekc Demo

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
  • This code works fine, but is better when you puts before the first and, after the last to build lines in the table! However, THANK YOU SO MUCH! – Jeff Monteiro May 14 '15 at 01:25
0
<?php
for($i = 1; $i++; $i<=30){
    ?>
    <tr>
     <td><?php print $dimension_.$i."_label"; ?></td>
     <td><?php print $dimension_.$i; ?></td>
  </tr>
    <?php
}
?>
Elyor
  • 5,396
  • 8
  • 48
  • 76
0

It would be easier if you redid your variable structure and used arrays, but using your current format you could do something like-

<?php
 for($i=1;$i<=30;$i++){
     if (${"dimension_".str_pad($i, 2, "0", STR_PAD_LEFT)."_label"}) { ?> 
  <tr>
     <td><?= ${"dimension_".str_pad($i, 2, "0", STR_PAD_LEFT)."_label"} ?></td>
     <td><?= ${"dimension_".str_pad($i, 2, "0", STR_PAD_LEFT)} ?></td>
  </tr>
<?php 
     }
  } 
?>
Sean
  • 12,443
  • 3
  • 29
  • 47
0

use something like this

$dimension[0] = something;
$dimension[1] = something;

and so on ...

and at time of printing them

for($i=0;$i<count($dimension);$i++)
{ ?>
<tr>
 <td><?= $dimension[$i] ?></td>
 <td><?= $dimension[$i] ?></td>
</tr>
<?php
}

?>
Master Yoda
  • 531
  • 8
  • 22