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 }; ?>
2
  • 1
    Make an array and loop over it Commented May 13, 2015 at 4:58
  • Yeah, instead of 30 variables, have one array like $dimension['$label'] = $value or$dimension[0] = array($label, $value) Commented May 13, 2015 at 5:12

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

Comments

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 
     }
  } 
?>

1 Comment

YOU ARE MY HERO! Thank you!
0
<?php
for($i = 1; $i++; $i<=30){
    ?>
    <tr>
     <td><?php print $dimension_.$i."_label"; ?></td>
     <td><?php print $dimension_.$i; ?></td>
  </tr>
    <?php
}
?>

3 Comments

this does not account for OPs 0 in 01, 02, etc.
you can use 'str_pad($i, 2, "0", STR_PAD_LEFT)' for that
first, in this case is necessary change the "for" putting $i++ after $i<30, however, in my case, using wordpress, this looping not print results...
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

1 Comment

This code works fine, but is better when you puts <tr> before the first <td> and, </tr> after the last </td> to build lines in the table! However, THANK YOU SO MUCH!
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
}

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.