Picking numbers from array..

Discussion in 'PHP' started by xenon2010, Dec 4, 2009.

  1. #1
    hi
    I have an array lets say the array has 3 elements:
    $array[] = 'myvalue1';
    $array[] = 'myvalue2';
    $array[] = 'myvalue3';

    now I have for loop which has 10 loops:
    for($i=0; $i<10; $i++)
    {
    echo $array[$i];
    }

    what I want is to pick a number from the given array each time the loop executes. in this way:
    myvalue1 picked in first loop execution.
    myvalue2 picked in second loop execution.
    myvalue3 picked in third loop execution.
    now I want to go back and pick myvalue1 again in the forth loop..
    and again in fifth loop it should pick myvalue2 and so on..

    I've been trying to do it for 1 day. and no luck..
     
    xenon2010, Dec 4, 2009 IP
  2. live-cms_com

    live-cms_com Notable Member

    Messages:
    3,128
    Likes Received:
    112
    Best Answers:
    0
    Trophy Points:
    205
    Digital Goods:
    1
    #2
    $index = $i % 3;
     
    live-cms_com, Dec 4, 2009 IP
    xenon2010 likes this.
  3. xenon2010

    xenon2010 Peon

    Messages:
    237
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #3
    where to add that?
     
    xenon2010, Dec 4, 2009 IP
  4. xenon2010

    xenon2010 Peon

    Messages:
    237
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    thanx that worked like charm...
    rep ++ :D
     
    xenon2010, Dec 4, 2009 IP
  5. n3r0x

    n3r0x Well-Known Member

    Messages:
    257
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    120
    #5
    The thing he showed you is called modulo (%)

    
    for($i=0; $i<10; $i++)
    {
       echo $array[($i%3)];
    }
    
    PHP:
    I would use it like that or for code that´s easier to read like:

    
    for($i=0; $i<10; $i++)
     {
       $i = $i%3;
        echo $array[$i];
     }
    
    PHP:
     
    n3r0x, Dec 4, 2009 IP
  6. akhil1311

    akhil1311 Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Use modulo (%) operator
    i%3 returns i if i<3 and it returns 0 when i=3 s that the value of index will always be 0,1,or 2. You can print indefinite times the array values.
    for($i=0; $i<10; $i++)
     {
       $i = $i%3;
        echo $array[$i];
     }
    PHP:
     
    akhil1311, Dec 4, 2009 IP
  7. xenon2010

    xenon2010 Peon

    Messages:
    237
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #7
    thank you all for your help... :)
     
    xenon2010, Dec 5, 2009 IP