How to Create unique array like lottery number?

✔ Recommended Answer

Something like this should work.

$arr = array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36");$user_data = json_decode(file_get_contents(__DIR__ . '/user.json'), true);$in_array = array();// Join all the numbers that exist into one arrayforeach ( $user_data as $user_datum ) {    $in_array = array_merge($in_array, $user_datum['lottery_number']);}// Get an array of numbers that don't exist in the user data $not_in_array = array_diff($arr, $in_array);unset($in_array);/* * Shuffle the array,  * then select the first 6 making a random array of unique numbers */shuffle($not_in_array);$random = array_slice($not_in_array, 0, 6);// $random is your final array

Source: stackoverflow.com

Answered By: Kalaghni

Method #2

To create a unique array of numbers, such as lottery numbers, in PHP, you can use a combination of the array_push() and array_unique() functions.

Here's an example code snippet to create an array of 6 unique random numbers between 1 and 50:

php
$lotteryNumbers = array(); while(count($lotteryNumbers) < 6) { $randomNumber = rand(1, 50); array_push($lotteryNumbers, $randomNumber); $lotteryNumbers = array_unique($lotteryNumbers); } sort($lotteryNumbers); echo "The winning lottery numbers are: " . implode(", ", $lotteryNumbers);

In this example, we first create an empty array called $lotteryNumbers.

We then use a while loop to generate random numbers between 1 and 50 and add them to the $lotteryNumbers array using array_push().

After each number is added, we use array_unique() to remove any duplicates from the array.

We keep generating and adding numbers until the array contains 6 unique numbers.

Finally, we sort the array in ascending order using sort() and print the winning numbers to the screen using implode().

You can adjust the number of lottery numbers, the range of possible values, and the format of the output as needed.

Comments

Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755