PHP array_rand() function
In this chapter you will learn:
- Definition for PHP array_rand() function
- Syntax for PHP array_rand() function
- Parameter for PHP array_rand() function
- Example - Get random values from an array
Definition
The array_rand()
function returns one or more random values from an array.
array_rand()
leaves the original array intact.
Syntax
PHP array_rand() function has the following syntax.
mixed array_rand ( array arr [, int amount] )
Parameter
Parameter | Is Required | Description |
---|---|---|
array | Required. | Get random value from array |
number | Optional. | How many random keys to return |
Example
Get random values from an array
<?php/* j a va 2 s. co m*/
$names = array("A", "B", "C", "D","java2s.com");
$two_names = array_rand($names, 2);
print_r($two_names);
print "\n";
$a=array("a"=>"A","b"=>"B","c"=>"C","j"=>"java2s.com");
print_r(array_rand($a,1));
print "\n";
print_r(array_rand($a,2));
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP array_reduce() Function
- Syntax for PHP array_reduce() Function
- Parameter for PHP array_reduce() Function
- Example - Reduce an array
- Example - Send initial value
- Example - return the sum
Home » PHP Tutorial » PHP Array Functions