Php Randomize Array (Shuffle)

images

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

2 Comments

2 Responses to “Php Randomize Array (Shuffle)”

  1. Erkman December 5, 2008 at 1:25 am #

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

  2. Pavel February 26, 2009 at 6:17 pm #

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

Leave a Reply

More in php (87 of 104 articles)


Propel Random Criteria >> $c= new Criteria(); $c->addAscendingOrderByColumn('rand()'); $TagRs = TagPeer::doSelect($c ); ?> This code will give you the ...