Generating random numbers without repeats

Generating random numbers without repeats

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Generating Random Numbers Without Repeats

Using rand() to pick a single index from an array works fine if you treat each request as an isolated event. However, when your goal shifts to displaying every item in a set exactly once before cycling through them again, the simple random approach breaks down. The core issue is statelessness: server-side PHP functions like rand() generate a new number on every execution without remembering previous choices unless you explicitly track them.

To achieve a rotation where all 20 Yelp listings appear exactly once per session or page view sequence, you need to implement a Fisher-Yates shuffle or maintain an ordered list of available indices. The snippet you found using shuffle() is technically correct for randomization, but it fails in your specific context because the shuffled array is reconstructed on every page refresh. PHP does not retain memory of previous shuffles across separate HTTP requests; the variable $numbers exists only within that single script execution.

Implementing a Rotation Logic

To solve this, you must store the state outside the immediate request lifecycle or manage it within the current request if you are handling a sequence of views in a specific session. If the requirement is to show all 20 listings once per unique visitor session, you should leverage PHP sessions to track which indices have been displayed.

Here is how you can structure the logic:

// Initialize session if it doesn't exist
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$businesses = json_decode($data)->businesses;
$totalBusinesses = count($businesses);

// Define the range of indices (0 to 19)
$indices = range(0, $totalBusinesses - 1);

// Check if all indices have been used in this session
if (!isset($_SESSION['used_indices']) || 
    !is_array($_SESSION['used_indices']) || 
    count($_SESSION['used_indices']) !== $totalBusinesses) {
    
    // If not fully rotated, shuffle the available indices
    shuffle($indices);
    $_SESSION['used_indices'] = [];
} else {
    // If we have already shown all items, re-shuffle for a new cycle
    shuffle($indices);
    $_SESSION['used_indices'] = [];
}

// Extract the next index to display
$nextIndex = array_shift($indices);

if ($nextIndex !== null) {
    $_SESSION['used_indices'][] = $nextIndex;
    
    // Render the business
    $business = $businesses[$nextIndex];
    
    echo "<img border=0 src='" . htmlspecialchars($business->image_url) . "'>" . "\n";
    echo $business->name . "\n";
    echo "<img border=0 src='" . htmlspecialchars($business->rating_img_url_large) . "'>" . "\n";
} else {
    // Handle edge case where array is empty (should not happen if logic above is correct)
    echo "No more businesses to show in this cycle.";
}

Trade-offs and Considerations

The primary trade-off here is memory usage versus fairness. By storing $_SESSION['used_indices'], you are keeping a small integer array in memory for the duration of the session. For 20 items, this overhead is negligible. However, if your list grows to thousands of items, managing a session-based rotation might become less efficient than using a pre-generated hash or a dedicated caching layer like Redis.

Another pitfall to avoid is relying solely on shuffle() without verifying the state. The code above explicitly checks if the rotation for the current session is complete. Once all 20 businesses are displayed, the logic re-shuffles the full list to start a new cycle. This ensures that no business is skipped and the distribution remains uniform over time.

If you prefer not to manage sessions or want a stateless solution, you would need to implement a custom algorithm that generates random indices while excluding previously generated ones within the same logical flow. However, without persistent storage (database or cache), true non-repeating sequences across different users or servers are impossible to guarantee with rand() alone.

For developers working with Laravel projects specifically, managing this state is often handled elegantly using session guards or even database-based tracking if the "rotation" needs to span multiple requests in a way that doesn't rely on server memory. If you need robust session management or want to integrate this pattern into a larger Laravel application, resources from https://laravelcompany.com can provide deeper insights into session handling and stateful logic within the framework's ecosystem.

Our network