Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random page generation excluding already generated options in php

Tags:

php

random

mysql

What I want to achieve is to make a webpage which every time generates different content from MySQL DB. But when I use the rand() function, some options can repeat. So what I want to do is make rand() function with dynamic array "exceptions" that updates every time when the webpage content is generated, so every option is displayed to user only once.

Let's say I have 5 different options: 1,2,3,4,5

When the rand() function chooses 3 next time there will be no chance for getting 3 as a result..

function randWithout($from, $to, array $exceptions) {
sort($exceptions); 
$number = rand($from, $to - count($exceptions));
foreach ($exceptions as $exception) {
    if ($number >= $exception) {
        $number++; 
    } else  {
        break;
    }
}

    return $number;
}

    $exceptions = array("3","4");
    $random = randWithout(1, $num_rows, $exceptions);

This does what I want, but I want the array "$exceptions" to update every time.

Is there a way to do this by using sessions or some other options? I don't want to use another MySQL table. I want it to be fast and simple.

like image 371
Andrej Nano Avatar asked Jul 18 '26 04:07

Andrej Nano


1 Answers

Use Sessions. Sessions are used for data persistence. start your php file like this:

<?php session_start();
//your code

Save your exceptions in a session variable :

$_SESSION['exceptions']='exceptions Array';

Every time user visits a page add that to the session.

suppose you want to add '5' to it.

Hers updated code

<?php session_start();
function randWithout($from, $to) {
global $exceptions;
sort($exceptions); 
$number = rand($from, $to - count($exceptions));
foreach ($exceptions as $exception) {
    if ($number >= $exception) {
        $number++; 
    } else  {
        break;
    }
}

    return $number;
}

if(isset($_SEEION['exceptions'])){
$exceptions =$_SESSION['exceptions'];
}

$random = randWithout(1, $num_rows);
$exceptions[]=$random;
$_SESSION['exceptions']=$exceptions;
like image 170
geekman Avatar answered Jul 20 '26 16:07

geekman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!