0

I've just recently updated my PHP to a newer version and have discovered that it's rendered some of my older, once functional code useless. Namely, since v5.2.10 with array_rand "the resulting array of keys is no longer shuffled" and therein lies the problem.

The following code doesn't work anymore, that is, it doesn't randomly shuffle like it used to:

$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);

//OUTPUTS:

$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

Any idea how to get that same functionality back?

Thanks.

Clarissa B
  • 239
  • 2
  • 5
  • 14
  • 2
    After a `foreach($array as &$valueref){` loop you should always `unset($valueref);` or you might run into very annoying and hard-to-debug problems (as soon as you assign something to `$valueref` which might be named less obvious in your code you are actually modifying the last array element) – ThiefMaster Apr 25 '11 at 09:52

1 Answers1

3
$rand = array_rand($in, 3);
shuffle($rand);
deceze
  • 510,633
  • 85
  • 743
  • 889