www.webdeveloper.com
Results 1 to 2 of 2

Thread: for() loop THIS! (please)

  1. #1
    Join Date
    Jun 2012
    Location
    FL, USA
    Posts
    48

    for() loop THIS! (please)

    Hello...

    I'm trying to figure out how to compact this here code into a nice for loop, but it is difficult:

    I'm considering something like (notice I simply want to just make a bunch of <tr>'s):
    Code:
    <?php
    for ($x = 1; $x <= 8; $x++)
    {
    print '
    <tr>
    	<td>$x</td>
    	<td><input type="text" maxlength="20" name="partno$x" value="<?php echo $partno$x ?>" /></td>
    	<td><input type="text" maxlength="100" name="part$xdesc" value="<?php echo $part$xdesc ?>" /></td>
    	<td><input type="text" maxlength="6" name="part$xqty" value="<?php echo $part$xqty ?>" /></td>
    	<td><input type="text" maxlength="8" name="part$xamount" value="<?php echo $part$xamount ?>"  /></td>
    	<td></td>
    </tr>
    ';
    }
    ?>
    for what I already have. Which is a huge chunk of code just repeating the same elements but with '$x' changed (numbers 1-8)...

    Thanks

  2. #2
    Join Date
    Jan 2004
    Posts
    484
    what you have is good
    lf you wanted to do it another way I feel that you'd be making you code convoluted.

    here is what I came up with

    PHP Code:

    $vpArr 
    = array(
                array(
    20,'partno$x'),
                array(
    100,'part$xdesc'),
                array(
    6,'part$xqty'),
                array(
    8,'part$xamount'),
    );


    function 
    spitHTML($x,$vpArr){
        
        
    $str '<tr>';
        
        foreach(
    $vpArr as $k => $v){
            
    $format '<td><input type="text" maxlength="%s" name="%s" value="%s" /></td>';
            
    $str .= sprintf($format$v[0],$v[1],$v[1]);
        }
        
        
    $str str_replace('$x'$x$str);
        
        return 
    $str.'</tr>';
        }

    echo 
    '<table>';

    for (
    $x 1$x <= 8$x++)
    {
    echo 
    spitHTML($x,$vpArr);    

    }
    echo 
    '</table>'

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles