Php random number not repeat

I'm building a website that will randomly display a yelp listing each time the page is refreshed. The yelp search api returns 20 listings in an array. Right now, I am using PHP's function rand[0,19] to generate a random listing every time the page is refreshed [ $businesses[rand[0,19]] ].

Can someone refer me to a smarter method to randomize? I want to show all 20 listings once before any of them are repeated. What is the preferred method to handle this problem?

the below answer doesn't work because the numbers are recreated every time I refresh the page. I'm guessing I need to store which numbers I've used already?

$numbers = range[0, 19];

shuffle[$numbers];
// Handle Yelp response data
$response = json_decode[$data];
$RANDOM = rand[1,19];
$business = $response->businesses;

echo "

ryankryank

3952 gold badges6 silver badges19 bronze badges

4

Easiest solution:

$numbers = range[1, 20];
shuffle[$numbers];

Alternative:


Similar question: #5612656

Codepad: //codepad.org/cBaGHxFU

Update:

You're getting all the listings in an array called $businesses.

  1. Generate a random listing ID using the method given above, and then store it your database table.
  2. On each page refresh, generate a random listing ID, and check if it matches the value in your database. If not, display that listing and add that value to your table.
  3. Go to step 1.

When this is completed, you will have displayed all the 20 listings at once.

Hope this helps!

answered Jul 22, 2013 at 1:37

Amal MuraliAmal Murali

73.9k18 gold badges126 silver badges145 bronze badges

1

try this code

$a = range[1,36];

shuffle[$a];

$array = array_slice[$a, 0, 3];

print_r[$array];

answered Aug 19, 2020 at 13:24

I would try this via while loop:


Method 2:



Method 3:



The above can randomly generate 5 non-repeating values between 1 and 20

Method 4:



Method 5:



This may be simpler than it is called [ps: If you specify a step size in range, you must pay attention to whether the second parameter of array_rand exceeds the length of $tmp].

PHP provides a very rich array function, most random numbers can be generated from the perspective of arrays, if you have methods to provide, welcome to give, the article will continue to update.

Chủ Đề