Basic function in PHP - help!!!

Discussion in 'PHP' started by pixelpie, Nov 2, 2007.

  1. #1
    Hi,

    I'm a bit of a newb and have just started studying PHP. I have a simple task to do but just can't find the info I need.

    The task is:

    Write a function grid ($x, $y) which prints out <table> in with size $x rows by $y columns with a unique number printed in every cell.


    :confused: Pleeease help!!!

    Thanks.
     
    pixelpie, Nov 2, 2007 IP
  2. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #2
    You have a number of ways you can do this. It will be a nested loop that you need.

    while, for..

    Personally I would do a nested for loop. Print one table row then print the next table row.

    
    function grid ($numx, $numy){
    $var = 0;
    echo '<table>';
    for($y=0;$y <= $numy; $y++;)
    {
      echo "<tr>";
      for($x=0;$x <= $numx; $x++;) 
      {
        $var++;
        echo "<td>$var</td>";
      }
      echo "</tr>";
    }
    echo '</table>';
    }
    
    PHP:
     
    exodus, Nov 2, 2007 IP
  3. pixelpie

    pixelpie Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3






    Exodus,

    thanks very much for your help. I added a couple of things to make a border around each cell and also to try and set the size of the grid at two columns and three rows.

    <?php

    function grid ($numx, $numy){
    $var = 0;

    echo '<table border="1">';

    for($y=0;$y <= $numy; $y++)
    {

    echo "<tr>";

    for($x=0;$x <= $numx; $x++)
    {
    $var++; echo "<td>$var</td>";

    }
    echo "</tr>";
    }

    echo '</table>';


    }

    grid(3,2);
    ?>



    However, the print out gives me 3 rows and four columns. Can you explain why this is, please?

    Thanks again.
     
    pixelpie, Nov 2, 2007 IP
  4. exodus

    exodus Well-Known Member

    Messages:
    1,900
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    165
    #4
    doh.. $x=0, $y=0.. Change those to $x=1, $y=1

    The basic idea is there though. Play around with it to figure out what a for loop does. :)
     
    exodus, Nov 2, 2007 IP
  5. pixelpie

    pixelpie Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Spot on, thanks so much. :)
     
    pixelpie, Nov 2, 2007 IP