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!

Get our RSS Feed!

Sponsors

Leave a Reply


* = required fields

(will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


  

CommentLuv Enabled