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

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 :(

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));

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";

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.