0

I have a requirement where I am randomely creating numbers from an array for a game, I have a for loop which goes around for 10 times and generates random number and summing it up. I am not sure whether this is a good solution or not, can anyone suggest me some changes if required?

$target = array(1,rand(1,5)); 
for ($i = 0; $i < 10; $i++) 
{ 
   $target = array_merge( $target, array(rand($i,5),rand(1,$i)) ); 
} 
echo '<pre>';
print_r($target);
Jaymin
  • 1,643
  • 1
  • 18
  • 39

1 Answers1

0

array_push is much faster than array_merge:

    $target = [1,rand(1,5)];

    for ($i = 0; $i < 10; $i++) 
    {
        array_push($target, rand($i, 5), rand(1, $i));
    } 

If you have only 10 iterations, then you may not see difference. E.g. with 10000 iterations comparison:

array_merge - 0.451275s
array_push - 0.003301s

Justinas
  • 41,402
  • 5
  • 66
  • 96