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:

array(
 1=>foo,
 2=>foo,
 3=>bar,
 4=>nothing,
 ...
)

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

$prices = array_fill(0, 99, '10');
$prices = array_fill(100, 139, '100');
$prices = array_fill(139, 149, '200');
$prices = array_fill(149, 150, 'reis');
($prices);

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.

function createTickets(Array $items, $totalItems) {

    $arr = [];
    // populate each item with $quantity
    foreach($items as $item => $quantity) {
        $arr = array_merge($arr, array_fill(0, $quantity, $item));
    }
    // fill in the rest with 'nothhing'
    $arr = array_merge($arr, array_fill(0, $totalItems - array_sum($items), 'nothing'));

    // return the final result
    return $arr;
}

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.

$tickets = createTickets(['foo' => 50, 'bar' => 30], 100);

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.

// Randomly select an item from the array
$someItem = $tickets[array_rand($tickets)];

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.

// Select 10 items at random
foreach(array_rand($tickets, 10) as $key) {
    echo $tickets[$key], "n"; // do something with item here
}

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

shuffle($tickets);
foreach($tickets as $ticket) {
    // now each item is at random
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement