I have a nested array of arrays, and I want to shuffle the inner arrays. My code looks like this (simplified):
$a = array(array('banana', 'peach'), array('ding', 'dong'), array('oh snow'));
foreach ($a as &$arr) {
shuffle($arr);
}
var_dump($a);
The var_dump outputs this:
array(3) { [0]=> array(2) { [0]=> string(5) "peach" [1]=> string(6) "banana" } [1]=> array(2) { [0]=> string(4) "ding" [1]=> string(4) "dong" } [2]=> &array(1) { [0]=> string(7) "oh snow" } }
As you can see in the output, the first two subarrays work, but the third subarray is linked by reference in the output…
In my full app, this last array-link causes problems, but rather than working around the issue, I want to fix this shuffle thing…
Cheers!
This has to do with how PHP stores references to array elements. It cannot reference an element of an array, only values. Therefore it has to store the value
array('oh snow')in a “slot” of the symbol table, then make$arrand$a[2]a reference to that value.To fix this,
unset($arr)after the loop. That way only a single variable is referencing the value, which will then be made a regular array index again. Unsetting references after aforeachis good practice anyway, since there are many such gotchas.