Jump to: navigation, search

Php array rand

From w3cyberlearnings

Contents

PHP function array_rand

This function returns one or more random key from a given array.

Syntax array_rand

  • array: array input
  • number: how many random keys to be return
array_rand(array, number);

Example 1

<?php

$president = array(
	 'George Washington' => 'April 30, 1789',
	 'John Adams' => 'March 4, 1797',
	 'Thomas Jefferson' => 'March 4, 1801',
	 'James Madison' => 'March 4, 1809',
	 'James Monroe' => 'March 4, 1817',
	 'Andrew Jackson' => 'March 4, 1829');

print_r(array_rand($president, 2));
?>


Output

  • Output is random, you may get a different result
Array ( [0] => George Washington [1] => Thomas Jefferson )

Example 2


<?php

$president = array(
	 'George Washington' => 'April 30, 1789',
	 'John Adams' => 'March 4, 1797',
	 'Thomas Jefferson' => 'March 4, 1801',
	 'James Madison' => 'March 4, 1809',
	 'James Monroe' => 'March 4, 1817',
	 'Andrew Jackson' => 'March 4, 1829');

for ($i = 0; $i < 3; $i++) {
	$count = 0;
	$select = array_rand($president, 2);
	echo $i . ' : ';
	echo $select[0];
	echo '--';
	echo $select[1];
	echo '<br/>';

}

?>


Output

  • You may have a different result according to the random key generate.
0 : George Washington--Andrew Jackson
1 : James Monroe--Andrew Jackson
2 : James Madison--Andrew Jackson


Related Links


Navigation
Web
SQL
MISC
References