note 80586 modified in function.shuffle by danbrown

From: Date: Fri, 25 Jul 2008 17:41:29 +0000
Subject: note 80586 modified in function.shuffle by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-142714@lists.php.net to get a copy of this message
Function that does the same as shuffle(), but preserves key=>values. (Based on (Vladimir Kornea of typetango.com)'s function) <?php function shuffle_assoc(&$array) { if (count($array)>1) { //$keys needs to be an array, no need to shuffle 1 item anyway $keys = array_rand($array, count($array)); foreach($keys as $key) $new[$key] = $array[$key]; $array = $new; } return true; //because it's a wannabe shuffle(), which returns true } $test = array(1=>'one','two'=>'2',3=>'3'); print_r($test); shuffle_assoc($test); print_r($test); ?> Array ( [1] => one [two] => 2 [3] => 3 ) Array ( [two] => 2 [1] => one [3] => 3 ) --was-- Function that does the same as shuffle(), but preserves key=>values. (Based on Vladimir's function) <?php function shuffle_assoc(&$array) { if (count($array)>1) { //$keys needs to be an array, no need to shuffle 1 item anyway $keys = array_rand($array, count($array)); foreach($keys as $key) $new[$key] = $array[$key]; $array = $new; } return true; //because it's a wannabe shuffle(), which returns true } $test = array(1=>'one','two'=>'2',3=>'3'); print_r($test); shuffle_assoc($test); print_r($test); ?> Array ( [1] => one [two] => 2 [3] => 3 ) Array ( [two] => 2 [1] => one [3] => 3 ) http://php.net/manual/en/function.shuffle.php

« previous php.notes (#142714) next »