Multidimensional Array at Random

I want to make my multidimensional array in random order. How do you do this?

// This is how the array looks like print_r($slides); Array ( [0] => Array ( [id] => 7 [status] => 1 [sortorder] => 0 [title] => Pants ) [1] => Array ( [id] => 8 [status] => 1 [sortorder] => 0 [title] => Jewels ) [2] => Array ( [id] => 9 [status] => 1 [sortorder] => 0 [title] => Birdhouse ) [3] => Array ( [id] => 10 [status] => 1 [sortorder] => 0 [title] => Shirt ) [4] => Array ( [id] => 11 [status] => 1 [sortorder] => 0 [title] => Phone ) ) // This how the result is if I use array_rand() print_r(array_rand($slides, 5)); Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 ) // This how the result is if I use shuffle() print_r(shuffle($slides)); 1 
+7
source share
4 answers

shuffle() is the way here. It prints 1 because shuffle modifies the array in place and returns a boolean value, as written in the documentation :

Returns TRUE on success or FALSE on failure.

I suggest also reading the documentation for array_rand() :

Selects one or more random entries from the array, and returns the key (or keys) of the random entries.


Always read the documentation if you use the built-in functions. Do not just assume how work. I bet it took more time to write a question than to look at it.

+17
source

Instead

 print_r(shuffle($slides)); 

do

 shuffle($slides); print_r($slides); 

You see shuffle() shuffles the array in place

+1
source

I'm not sure how you want to display it, but you can encode the array and use the php rand (0, arraylen) function to parse the array.

+1
source

It works great. print_r (shuffle ($ slides))) gives the result TRUE, since the return value of shuffle is a boolean, not an array.

See a working example here: http://codepad.org/B5SlcjGf

0
source

All Articles