php loop

Discussion in 'PHP' started by red_fiesta, May 7, 2007.

  1. #1
    I have the code

    <? $i=0; 
    
    while ($i < 11){ 
    
    ?>
    
    <option value="<? print date('n', strtotime('-1 Month')); ?>"> <? print date('M', strtotime('-1 Month')); ?></option>
    <?
    
     $i++; 
    
    }
    
    ?>
    	
    Code (markup):
    i need to chage the print date('n', strtotime('-1 Month')); to not be -1 but be - i how do i do this seeing as i am already within the <? ?>

    Thanks
     
    red_fiesta, May 7, 2007 IP
  2. red_fiesta

    red_fiesta Peon

    Messages:
    125
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    worked it out

    <option value="<? print date('n', strtotime('-'.$i.' Month')); ?>"> <? print date('M', strtotime('-'.$i.' Month')); ?></option>
     
    red_fiesta, May 7, 2007 IP
  3. rodney88

    rodney88 Guest

    Messages:
    480
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    0
    #3
    strtotime('-' . $i . ' Month')

    You could also compact the whole thing into a for loop:
    <?php
    for ( $i = 0; $i < 11; $i++ ) {
        $time = strtotime('-' . $i . ' Month');
        echo '<option value="', date('n',$time), '">', date('M',$time) ,'</option>';
    }
    PHP:
     
    rodney88, May 7, 2007 IP
  4. clancey

    clancey Peon

    Messages:
    1,099
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    0
    #4
    For another variation, this worked for me:

    $i = 0; 
    
    while ($i < 11){ 
    
     print '<option value="' . 
        date('n', strtotime("-$i Month")) . '">' . 
          date('M', strtotime("-$i Month")) . '</option>';
     $i++; 
    }
    
    PHP:
    The output went from May to July, with the option value number matching number of the month, in that May==5 and January==1.
     
    clancey, May 7, 2007 IP
  5. brox4motto

    brox4motto Peon

    Messages:
    28
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    I would recommend you to get familiar with Smarty (smarty.php.net). It's a PHP template engine which allows you to separate HTML from PHP completely.
    It's smarter than you think, so give some and read a little bit of manual.

    I did some of my sites using it and never looked back to old methods (putting HTML in PHP code)!!!
     
    brox4motto, May 7, 2007 IP