Square root and cube number in a table

Asked

Viewed 727 times

2

I am learning PHP and I have a job where I have to do the square root and cube of the numbers from 1 to 10, displaying in a table with PHP. I’ve managed to put the square root of the numbers 1 to 10 all in a square and the same with the cube, but to mount the table in PHP, it’s not working. I have to wear the bow for. How can I separate each root and cube from the next number?

I used this code:

<!doctype html>
<html>
  <head>
    <title></title>
  </head>

  <body>
    <table border=1>
      <tr>
        <th>Cube</th>    
        <th>Square root</th>
      </tr>
      <tr>    
        <td>
          <?php
            //Cube 
            for($i=1; $i<=10; $i++) {
              echo "$i^3 = ". pow($i,3) . "<br />";
            }
          ?>
        </td>
        <td>
          <?php
            //Square Root
            for($i=1; $i<=10; $i++) {
              echo "√$i = ".sqrt($i) . "<br />";
            }
          ?>
        </td>
      </tr>
    </table>
  </body>
</html>

2 answers

2

You can store them in an array

<?php
for($i=1; $i<=10; $i++) {
    $rs['cube'][$i] = pow($i,3);
    $rs['sqrt'][$i] = sqrt($i);
}
?>

With this you can manipulate the data as you wish.

But it is not very clear which result you want in HTML.

2

I think what you want is this:

<!doctype html>
<html>
  <head>
    <title>Raiz quadradas e cubos</title>
  </head>

  <body>
    <table border="1">
      <tr>
        <th>n</th>
        <th>Cube</th>    
        <th>Square root</th>
      </tr>
      <?php for($i=1; $i<=10; $i++) { ?>
        <tr>
          <td><?php echo $i; ?></td>
          <td><?php echo "$i^3 = " . pow($i, 3); ?></td>
          <td><?php echo "√$i = " . sqrt($i); ?></td>
        </tr>
      <?php } ?>
    </table>
  </body>
</html>

That is, if you want to build table rows in HTML, your for should iterate lines, not individual values of each column.

Also note that you do not need to add <br /> inside the cells of your table.

See it working on ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.