0

I want to make an array with a random amount of values between 2 and 5.

Each value would be 50.

What's the easiest way to do this?

eg:

$array = array(50,50,50,50)
$array = array(50,50)

4 Answers 4

2

$array = array_fill(0,rand(2,5), 50) is the simplest I can think of.

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

Comments

2

Try with:

$array = array_fill(0, rand(2, 5), 50);

Comments

0
$array = array();
for($i = 0, $max = rand(2,5); $i < $max; $i++) $array[] = 50;

This will create an array with 2 to 5 items with the value 50.

Edit: An easier solution is to use array_fill():

$array = array_fill(0, rand(2, 5), 50);

Comments

-1

Take a look at mt_rand(). To generate a random number between 2 and 5 (inclusive):

$random = mt_rand(2, 5);

4 Comments

@TimWolla: Why the -1? Not coding it for him does not mean my answer is not helpful to him, or others reading this.
In my opinion this is not helpful enough. Simple as that.
@TimWolla: In my opinion, you're missing the point of a +1/-1 system if you think "not helpful enough" warrants a -1. Just don't vote on it at all if it's "not helpful enough." It's not incorrect, and not bad advice, and it could be helpful to others. Simple as that.
Seems like you are right. But sadly I can no longer remove the downvote :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.