Skip to content
Advertisement

Generate a PHP array with 100 tickets and a random number to compare

I am new to symfony and I am trying to make a function that generates a random number and then I want to check this random number in an array of prices. Let’s say there are 100 tickets so 100 items in the array. 50 of them are a price “foo” 30 “bar” and 0 “win nothing”.

My goals is to populate this array at random so it should look like this:

JavaScript

EDIT here is what i’ve tried but doesn’t seem to be working. The array is being filled with only the last fill

JavaScript

I have no idea how to populate my array at random and could use all the help in the world

Any help would be realy awesome!

Thanks in advance!

Advertisement

Answer

Your problem can be broken up into two simple parts. First, you need to create an array with an arbitrary number of values, which you could do with a function like this, as per your requirements described above.

JavaScript

So, to create an array of 100 items, with 50 foo and 30 bar, and the rest are nothing, you would do something like this.

JavaScript

Second, you need to select items at random from the array you created.

The actual order of the elements in the array doesn’t matter. You can use something like shuffle to randomize the order of elements in the array, but that’s not necessary, because you can always select items from the array at random using array_rand, for example.

JavaScript

Becuase you already know how many items you’re creating in the array, you can always supply the amount of random items to extract to array_rand.

JavaScript

If you prefer to just shuffle the array because you intend to consume the entire array at random you could just do that instead.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement