This following piece of code is meant to create a multilevel array, print it, then shuffle it, again print it, and sort the array.
$arr=array(
array(
array('a','b','c')
),
array(
array('d','e','f')
),
array(
array('g','h','i')
),
);
print_r($arr);
shuffle($arr);
print_r($arr);
sort($arr);
print_r($arr);
Now the odd thing that i observed, when shuffle() is used, it only shuffles the indexes of the array that is being shuffled, it doesnt shuffle, the inner most elements a,b,c to something else, but when the the sort() function is used, it sorts back the array into the normal status and the leaf nodes are back to alphabetical order. Why does this happen?
Here is the sample output:
*Original Array*
Array
(
[0] => Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
)
[1] => Array
(
[0] => Array
(
[0] => d
[1] => e
[2] => f
)
)
[2] => Array
(
[0] => Array
(
[0] => g
[1] => h
[2] => i
)
)
)
Shuffled Array
Array
(
[0] => Array
(
[0] => Array
(
[0] => g
[1] => h
[2] => i
)
)
[1] => Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
)
[2] => Array
(
[0] => Array
(
[0] => d
[1] => e
[2] => f
)
)
)
Sorted Array
Array
(
[0] => Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
)
[1] => Array
(
[0] => Array
(
[0] => d
[1] => e
[2] => f
)
)
[2] => Array
(
[0] => Array
(
[0] => g
[1] => h
[2] => i
)
)
)
See the array section of PHP’s comparison operator reference, especially the array comparison transcription. Basically PHP first compares the amount of keys in the array, then checks if the arrays have the same keys (in this case,
0for the inner arrays) and then compares the values. Because you have a nested array there, it proceeds to compare the leaf nodes insort(), which leads to the array being sorted in this case by the first value of the leaf arrays (a,dandg).shuffle()simply reorders the indexes of the array you give it regardless of what the array contains, thus it does not touch the inner arrays at all.