-1

I try to create a variable who send a random value !

 $random = mt_rand(5,10);

but i want the variable random with the number i choose like this:

$random = 5;10;15;20;25;30

The variable must send randomly 5 or 10 or 15 or 25 or 30 only

psppro26
  • 25
  • 5

10 Answers10

1

Like that?

$random = mt_rand(1,6) * 5;
Paladin
  • 1,637
  • 13
  • 28
1

What you could do is using the mt_rand function with values from 1 to 6 then multiply them by 5.

Example:

$random = mt_rand(1, 6) * 5;
Ad5001
  • 748
  • 5
  • 19
1

Use array_rand to pick random key from array then you can put it into an another.

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

$input = array(5,10,15,20,25);
$rand_key = array_rand($input);
$another_array[] = $input[$rand_key];
Peter
  • 748
  • 6
  • 20
  • This has the advantage that it allows you to update the numbers when needed, rather than needing to work out the calculation for it, such as if you needed 13 adding at some stage. – gabe3886 Apr 24 '17 at 11:33
  • Yes, this is only one approach there is a lot. I wanted to show something like alternative solution :) It depends on the real cause what uses needed that :) – Peter Apr 24 '17 at 11:37
0

You could use and array of element and get a random item

   $items = Array(5,10,15,20,...50);

    $myvalue = array_rand($items);
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

Assuming that you already have the values you want inside an array you can simply get a random position of the array. A rand() limited by the first element to the size of the array can solve this

<?php

$valores = [1,5,12,17,22,30,90,2,4,6]; // choose de values here

for($i=0;$i<200;$i++){ // just to print more than 1 value 
    echo $valores[rand(1,sizeof($valores))-1]."<br>"; // really pick the values here. start in 1 because we'll remove 1 
}
Xidh
  • 582
  • 1
  • 5
  • 19
0

Will it always be steps of 5? Then you could do something like

$random = mt_rand(1,6) * 5;

Otherwise I'd put the numbers that you want to choose from in an array and select a random element using mt_rand():

$random_temp = array(3,6,8,13,16,19);
$random = $random_temp[mt_rand(0,6)];
0

If the random numbers arrayed, then this may help:

$list=array(5,10,15,20,25,30);
$n=count($list)-1;
$random=$list(rand(0,$n));
0
$values = [5,10,15,20,25,30];
//shuffle the array
shuffle($values);
foreach($values as $v){
  print $v;
}

always in different order...

JustOnUnderMillions
  • 3,741
  • 9
  • 12
0

You can use rand():

$random = rand(1, 6) * 5;

Will produce:

5, 10, 15, 25 or 30 randomly.

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
0

Please try this code

$random = rand(0,30);

if(($random%5)==0)
{
    echo $random;
}
else
{
    echo roundUpToAny($random);
}
function roundUpToAny($n,$x=5) {
    return round(($n+$x/2)/$x)*$x;
}