0

The following code generates random number from 1 to 10

$ran = rand(1,10);

What if i want random numbers from my custom values.that is (1,3,6,7,9)


for example i need to generate any one number from the group (1,3,6,7,9)

3 Answers 3

1

You can do that as following,

<?PHP

$numbers = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6);
$random_key = array_rand($numbers, 1);
print $random_key;

?>
Sign up to request clarification or add additional context in comments.

3 Comments

The keys here are reluctant. using $numbers[array_rand($numbers)] is enough.
WAIT..i want this value (1,3,6,7,9) ,,,1 => 5, 2 => 9, 3 => 6, 4 => 9, 5 => 11, 6 => 4); when i do like that i get 1,2,3,4,5, only
@PankajjKumar: It's the keys which matter in this example.
1

You want array_rand()

or you could shuffle() and always just reference $array[0] which would also be "random"

2 Comments

You should try and provide an example
I'd rather have anyone searching or the OP to learn to utilize the PHP manual than just get specific examples on SO. Understanding the direct source with examples is more important than providing a specific example to the OP's case, in my opinion.
0

You need array_rand function for that . the Parameters are array_rand ( array $input [, int $num_req = 1 ] ) . For your purpose , use it as $var_rand = array_rand($arr); as you want only 1 random number generated . For more help, refer to this

Also , for future questions , post your php version too. Some functions are not available in older versions . This one is available , though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.