SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Guru
    Join Date
    Dec 2005
    Posts
    964
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Move 2 records from array to array randomly?

    I'm trying to figure out how to get 2 or more records moved from one array to another randomly?

    This is what I have so far:
    PHP Code:
    $array1 = array('1','2','3','4','5','6','7','8','9');

    $random rand(0,sizeof($array1)-1);

    $getfromarray $array1($random);

    unset(
    $array1[$random]); 
    As above I can get one number from the array above and remove it from the array, but not sure how to get multiple from the array and how to insert it into a new array?

    Please help and thanks in advance :-)

  2. #2
    Non-Member
    Join Date
    Jan 2012
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try this:

    Code PHP:
    <?php
    $array1 = array('1', '2', '3', '4', '5', '6', '7', '8', '9');
    $array2 = array();
    $numElements2del = 3;
    for ($i = 0; $i < $numElements2del; $i++) {
        $random = rand(0, sizeof($array1) - 1);
        $array2[] = $array1[$random];
        array_splice($array1, $random, 1);
    }
    print_r($array1);
    print_r($array2);
    ?>

  3. #3
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,053
    Mentioned
    66 Post(s)
    Tagged
    0 Thread(s)
    If you don't care about maintaining the order of the elements in the source array, you can shuffle it and pop off two elements. If you are trying to simulate playing cards this is likely the better solution since the deck state can be maintained over time.

    Code php:
    $array1 = range(1,9);
    $array2 = array();
     
    shuffle($array1);
     
    $array2[] = array_pop($array1);
    $array2[] = array_pop($array1);


Bookmarks

Posting Permissions

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