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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.