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
- array_change_key_case
- array_chunk
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_key_ exists
- array_keys