Display Values from an Array in Random Order
Posted on October 2, 2008, Filled under PHP,
Bookmark it
This is a function that randomizes the order of the elements in an array.
<?php
function randomize_array($array)
{
$rand_items = array_rand($array, count($array));
$new_array = array();
foreach($rand_items as $value)
{
$new_array[$value] = $array[$value];
}
return $new_array;
}
$array = array('sleep' => 'Delay execution',
'show_source' => 'alias for highlight_file()',
'str_ireplace' => 'PHP5 Function',
'sizeof' => 'Alias for count',
'parse_url' => 'Parse a URL and return its components');
echo "<pre>"; print_r($array); echo "</pre>";
echo "<pre>"; print_r(randomize_array($array)); echo "</pre>";
/*
-- Initial Array
Array
(
[sleep] => Delay execution
[show_source] => alias for highlight_file()
[str_ireplace] => PHP5 Function
[sizeof] => Alias for count
[parse_url] => Parse a URL and return its components
)
-- An example of a random result
Array
(
[sizeof] => Alias for count
[parse_url] => Parse a URL and return its components
[sleep] => Delay execution
[str_ireplace] => PHP5 Function
[show_source] => alias for highlight_file()
)
*/
?>
NOTE: A similar function in PHP is shuffle() which assigns new keys to elements in the array. It removes any existing keys that may have been assigned, instead of just reordering them as our randomize_array() function does.
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- October 2, 2008
- article by Gabriel C.
- Leave a reply!
Sponsors
Related Posts
-
PHP: How to remove empty values from an arrayat May 21, 2008 with 6 comments
-
PHP: How to select a random value from an array using a specified rangeat September 20, 2008
-
Creating a Random Quote Scriptat August 29, 2008 with 2 comments
-
PHP: Make an Alphabetical Selection from Elements of an Arrayat October 5, 2008
-
How to generate a random password in PHPat August 29, 2008 with 2 comments
