Home > Net >  PHP -- How to multiple random numbers?
PHP -- How to multiple random numbers?

Time:02-01

Very new to coding here. Trying to get five random numbers in a range from -10 to 10 generated at once. I have another .php file in which I use the roll_num function, but I'm trying to avoid writing the function 5 different times.

Here is what I currently have:

function roll_num()
{
    for ($result = 0; $result <= 5; $result  )
    {
        $result = [];
        $result = rand(-10, 10);
        return $result;
    }
}

Looking for the simplest way to write this. Help would be useful as I don't know what I'm doing, and this is for an introductory class lol. The way I'm trying is similar to the class example, so I'd like to keep it about the same so that I can follow alongside the course without getting too lost. (Besides what I need to change, of course!) Thanks in advance!

CodePudding user response:

The problem with your code is the return inside of the for loop. As soon you hit the return command the function will exit returning the current value of the result, with only one element. Your return should be out of the for loop.

Try something like this:

function roll_num()
{
    $result = []; // result should start empty
    for ($result = 0; $result <= 5; $result  )
    {
        // every step of the loop should add random value to the array
        $result[] = rand(-10, 10);
    }
    // after all random values were pushed, you return once
    return $result;
}

CodePudding user response:

In your code, you are saving the random number in a variable result and immediately returning it. You should keep an array outside the loop and add numbers to it iteratively. Also the iterator should be a seperate integer not your array itself which should end at index 4.

<?php

function roll_num()
{
    $result = [];
    for ($i = 0; $i < 5; $i  )
    {
        $result[] = rand(-10, 10);
    }
    return $result;
}

print_r(roll_num());

CodePudding user response:

function roll_num()
{
  $min = -10;
  $max = 10;
  $num = 5;
  $count = 0;
  $return = [];
  while ($count < $num) {
    $return[] = mt_rand($min, $max);
    $return = array_flip(array_flip($return));
    $count = count($return);
  }
  shuffle($return);
  return $return;
}


print_r(roll_num());

  •  Tags:  
  • Related