Sep 27 2007

Php Randomize Array (Shuffle)

images.jpg

If you want to randomize a php array , you can use shuffle function.

But we can’t randomize the whole array with its value, it might be integer, string or collection of objects etc. So we randomize or shuffle the keys of the array.

Eg:

$Keys = array_keys($MyArray);
shuffle($Keys);

$NewArray = array(); //declare a new array
foreach( $Keys as $key)

{

$NewArray[] = $MyArray[$key];

}

Here the NewArray will be the shuffle of MyArray

Thanks

Sajith.M.R

TAGS:

2 Comments on this post

Trackbacks

  1. Erkman said:

    It doesn’t work. It shuffles the keys, but some keys have been lost after shuffling. Bad tip… :(

    December 5th, 2008 at 1:25 am
  2. Pavel said:

    No code is right. it’s works. Erkman makes something wrong.
    BUT IT IS NOT RANDOMIZE…

    February 26th, 2009 at 6:17 pm

LEAVE A COMMENT

Subscribe Form

Subscribe to Blog

Recent Comments

  • Sajith M.R: Press shift and enter key for a new line in chat
  • Borellus: Nice little function there, I think I may try to use it at some point.
  • Abhishek: Can we have newline characters…. i want something like this Line 1 Line 2 Line 3
  • Joanne Cox: Thanks for sharing this; your input is appreciated and has made me change my opinion slightly. About the...
  • Saboor: hi i also want to implement a chatting like Gmail or FaceBook , please, email me the source code on...

Recent Posts