How shuffle array and remove a $value1 after echo...

Discussion in 'PHP' started by anilinkz, Feb 22, 2011.

  1. #1
    i have this array

    <?php $colors = array('red' ,'white' ,'blue' ,'yellow' ,'black'); ?>
    PHP:
    i want to echo only 4 of colors on 4 lines randomly (without repeating the color) so i use the shuffle() command

    but i can only show the color 'red' on the first line only so i need to remove the 'red' from the array after the first echo so that 'red' won't show up on the 2nd 3rd and 4th line.

    some sample output...
    TIA
     
    anilinkz, Feb 22, 2011 IP
  2. jkl6

    jkl6 Peon

    Messages:
    70
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Instead of trying to remove 'red', just do a check for "if (red) then skip printing". To make sure that you print 4 colors, use a variable to count the number of times you print.
     
    jkl6, Feb 22, 2011 IP
  3. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #3
    Haven't tested it but it should work ok...
    
    <?php
    $colors = array('red' ,'white' ,'blue' ,'yellow' ,'black');
    while(is_array($colors) && count($colors) >= 0)
    {
    $colors = shuffle($colors);
    echo array_pop($colors);
    }
    ?>
    
    PHP:
     
    tvoodoo, Feb 22, 2011 IP
  4. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #4
    If you wish to display 4 random colors from the array one below the other, then you don't need to put any condition OR need not remove any element from array.

    Simply do shuffle and print first 4 elements.

    I wonder, why would you need to keep 'red' in first line only?
     
    mastermunj, Feb 23, 2011 IP