Jump to content

[SOLVED] Random selection from pre-defined set


Michan

Recommended Posts

Okay, so I know how to create a random number from min and max values, but how do I create a random number from a pre-defined set of numbers?

 

Say for instance, I have the numbers 1, 3, and 7 - and I want to select a random number of those three, how would I get about doing it?

 

Thanks in advance.

 

- Mi

Link to comment
Share on other sites

Well, a simpler idea is the following.

 

$something = array("add some array values in here");
shuffle($something);
echo $something[0];

 

Thank you very much, this works perfectly!

 

And thanks phpQuestioner, but the rand() requires min and max values, so it didn't work :(

Link to comment
Share on other sites

FYI:

you could also do this (if you want to use an array)

<?php
$mypic = array("1","3","7");
$rand = array_rand($mypic);
echo $mypic[$rand];
?>

 

EDIT: also rand does NOT Require a min & max, they are optional

but in phpQuestioner, code it should be

rand(0, count($mypicks));

Link to comment
Share on other sites

Thanks MadTechie; I thought that would work; But I did leave out some code - did not test it - lol.

 

Here is also another way to use rand() - I use this for random text and images:

 

<?php

$mypicks[] = "1";
$mypicks[] = "3";
$mypicks[] = "7";

srand ((double) microtime() * 1000000);
$picknums = rand(0,count($mypicks)-1);

$picks = $mypicks[$picknums];

echo "$picks";

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.