note 56291 deleted from function.array-rand by cmb

From: Date: Sun, 18 Oct 2020 11:01:42 +0000
Subject: note 56291 deleted from function.array-rand by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-215608@lists.php.net to get a copy of this message
Note Submitter: bjcffnet at gmail dot com ---- As wazaawazaa600 at msn dot com pointed out, a multi-dimensional array doesn't work with this function. So, I hope I can help someone with this :) <?php /** * Returns a number of random elements from an array. * * It returns the number (specified in $limit) of elements from * $array. The elements are returned in a random order, exactly * as it was passed to the function. (So, it's safe for multi- * dimensional arrays, aswell as array's where you need to keep * the keys) * * @author Brendan Caffrey <bjcffnet at gmail dot com> * @param array $array The array to return the elements from * @param int $limit The number of elements to return from * the array * @return array The randomized array */ function array_rand_keys($array, $limit = 1) { $count = @count($array)-1; // Sanity checks if ($limit == 0 || !is_array($array) || $limit > $count) return array(); if ($count == 1) return $array; // Loop through and get the random numbers for ($x = 0; $x < $limit; $x++) { $rand = rand(0, $count); // Can't have double randoms, right? while (isset($rands[$rand])) $rand = rand(0, $count); $rands[$rand] = $rand; } $return = array(); $curr = current($rands); // I think it's better to return the elements in a random // order, which is why I'm not just using a foreach loop to // loop through the random numbers while (count($return) != $limit) { $cur = 0; foreach ($array as $key => $val) { if ($cur == $curr) { $return[$key] = $val; // Next... $curr = next($rands); continue 2; } else { $cur++; } } } return $return; } ?>

« previous php.notes (#215608) next »