Square root and cubed number on a table

2

I'm learning PHP and I have a job where I have to do the square root and the cube of the numbers from 1 to 10, displaying in a table with PHP. I have already managed the square root of the numbers from 1 to 10 all in a square and the same with the cube, but to mount the table in PHP, it is not working. I have to use the for loop. How can I separate each root and cube from the following 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>
    
asked by anonymous 21.02.2017 / 16:25

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's not clear what the result you want in HTML.

    
21.02.2017 / 16:55
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 must iterate the rows, not the individual values of each column.

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

See working on ideone.

    
21.02.2017 / 17:31