PHPLover PHPLover - 2 years ago 122
PHP Question

How to apply rand() or some other built-in function on an array that contains all string elements in order to randomly select a string?

I've a following array :

$family = array("Amit", "Suresh", "Vinit", "Somesh", "Sagar", "Shriram");


Now I want to randomly select a name from the above array.

How should I do this?

I know about rand() function. Even I tried
rand($family);
but it gave me Warning as below :

Warning: rand() expects exactly 2 parameters, 1 given in /var/www/project/index.php on line 7

It's asking for second argument.

So please someone help me in selecting a string randomly from an array that contains all string elements.

Thanks.

Answer Source

Read the docs first, there is exact function you are looking for in example

http://php.net/manual/en/function.array-rand.php

<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download