Search code examples
phparraysrandomsplitdelimited

Get 3 random elements from a flat array and split each element by its delimiter


I'm trying to get random values out of an array and then break them down further, here's the initial code:

$in = array('foo_1|bar_1', 'foo_2|bar_2','foo_3|bar_3','foo_4|bar_4','foo_5|bar_5' );
$rand = array_rand($in, 3);

$in[$rand[0]]; //foo_1|bar_1
$in[$rand[1]]; //foo_3|bar_3
$in[$rand[2]]; //foo_5|bar_5

What I want is same as above but with each 'foo' and 'bar' individually accessible via their own key, something like this:

$in[$rand[0]][0] //foo_1
$in[$rand[0]][1] //bar_1

$in[$rand[1]][0] //foo_3
$in[$rand[1]][1] //bar_3

$in[$rand[2]][0] //foo_5
$in[$rand[2]][1] //bar_5

I've tried exploding $rand via a foreach loop but I'm obviously making some n00b error:

foreach($rand as $r){
    $result = explode("|", $r);  
    $array = $result;
}

Solution

  • Try this:

    $in = array('foo_1|bar_1', 'foo_2|bar_2','foo_3|bar_3','foo_4|bar_4','foo_5|bar_5' );
    
    foreach ($in as &$r) {
      $r = explode("|", $r);  
    }
    
    $rand = array_rand($in, 3);
    

    That modifies all of the values of the $in array by reference, so after the loop, all strings have been split into two subarray elements.

    Now, use the indexed results of the$rand array to access three of the rows from the mutated $in array.

    $in[$rand[0]][0] //foo_1
    $in[$rand[0]][1] //bar_1
    
    $in[$rand[1]][0] //foo_3
    $in[$rand[1]][1] //bar_3
    
    $in[$rand[2]][0] //foo_5
    $in[$rand[2]][1] //bar_5