PHP - Truly Random Number Each Page Load

User 2733 Photo


Ambassador
426 posts

<?php
session_start();
$r = range(1,10);
$random = ($_SESSION['random']) ? $_SESSION['random'] : 1;
$key = array_search($random, $r);
unset($r[$key]);
shuffle($r);
$_SESSION['random'] = $r[0];
echo $_SESSION['random'];
?>


// leave this so we can assign a session key/value pair to the last number used, must go at top of page before any other output
session_start();

// create a range of numbers between x and x to use as the seed
$r = range(1,10);

// if the session var is set, use it otherwise use 1 OR whatever the low range value is above
$random = ($_SESSION['random']) ? $_SESSION['random'] : 1;

// search for the $random value and remove it so we don't use it again without using another value first
$key = array_search($random, $r);

// deleting the value from this page load only
unset($r[$key]);

// shuffling the array for sequential random behavior
shuffle($r);

// creating a session var from $r to use as the array pointer
$_SESSION['random'] = $r[0];

// we're just echoing the result here. it can also be assigned to a var
echo $_SESSION['random'];
Let's not get all hurt.
User 364143 Photo


Guest
5,410 posts

If it's seeded, is it truly random?
CoffeeCup... Yeah, they are the best!
User 38401 Photo


Senior Advisor
10,951 posts

I would think so as long as the number is random from the range it has to choose from and doesn't follow any specifically set patterns.
User 364143 Photo


Guest
5,410 posts

Of course it has to follow specifically set instructions. It's a computer program.
CoffeeCup... Yeah, they are the best!
User 38401 Photo


Senior Advisor
10,951 posts

well ya lol, but as long as you don't set a specific pattern for the numbers to show up is what I mean. Yes it has to follow a pattern to get to the point of grabbing the number, but if there's no pattern for what number it's going to grab and subsequent choices of the number then it would be randomly chosen from a set array of numbers right?
User 2733 Photo


Ambassador
426 posts

@Jo Ann Thank you.
Let's not get all hurt.
User 364143 Photo


Guest
5,410 posts

:P
CoffeeCup... Yeah, they are the best!
User 244141 Photo


Ambassador
1,209 posts

Where do you think I get the number for displaying my online visitors from??..:P:lol: joking,..or not..no really joking...or am I, lol
Web Design: https://www.websnoogie.com
Member - BBB: Websnoogie, LLC







Have something to add? We’d love to hear it!
You must have an account to participate. Please Sign In Here, then join the conversation.