help with code to display random numbers

Discussion in 'PHP' started by mog08, Jul 13, 2008.

  1. #1
    I'd be grateful if someone could help with the following.

    I have a wordpress theme that contains the following piece of code in index.php where the array corresponds to wordpress category numbers - in this instance 1, 2 ,3 ,4 and 5

    <?php $display_categories = array(1,2,3,4,5); $i = 1;
    foreach ($display_categories as $category) { ?>


    I was wondering if there was an easy way to randomly show links to any five categories from a longer list of possibles.

    i.e. if the possibles are 1,2,3,4,5,6,7,8,9,10,11,12

    on first load show 1,3,5,2,6

    on refresh show 2,12,11,4,5

    on refresh show 3,6,1,7,12

    and so on.

    Many thanks in advance.

    Mog
     
    mog08, Jul 13, 2008 IP
  2. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #2
    $display_categories = array_rand(array_flip(range(1, 12, 1)), 5);
    PHP:
    5 is the number to show.
    12 is the maximum number to have.
    The 1 is the minimum number to have.

    Dan
     
    Danltn, Jul 13, 2008 IP
  3. mog08

    mog08 Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Hi Dan,

    Thanks for your help.

    Is there a way to actually specify the category numbers to use, rather than just pick from a range.

    i.e. If I have twelve categories in total but only want to show any five from say 1,2,3,4,6,8,10,11,12 and exclude 5,7,9

    Thanks again,

    Mog
     
    mog08, Jul 13, 2008 IP
  4. Danltn

    Danltn Well-Known Member

    Messages:
    679
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    120
    #4
    $display_categories = array(1, 2, 3, 4, 6, 8, 10, 11, 12);
    $display_categories = array_rand(array_flip($display_categories, 5);
    PHP:
     
    Danltn, Jul 14, 2008 IP