1

I am randomizing php templates to include them in the web page. Each time the user reloads the web page, a new randomized template will appear.

Problem with array_rand it returns one random string each time the user reloads the web page, and the same template may be displayed again and again.

For example, let's say the user reloads the page 3 times. He may get the following templates: template1.php, template1.php, template2.php

I want the user to see all the templates in a random order. For example, template3.php,template2.php,template1.php

$items = array("template1.php","template2.php","template3.php"); #templates array
$a = $items[array_rand($items,1)]; #randomize templates

include $a; #including randomized template

2 Answers2

1

You could use in if statement in combination with a $_SESSION[] variable to store the previous page and omit the previous page from the array before calling your rand procedure

session_start();
$items = array("template1.php","template2.php","template3.php");
if (($key = array_search($_SESSION['last_page'], $items)) !== false) {
    unset($items [$key]);
} //taken from https://stackoverflow.com/questions/7225070/php-array-delete-by-value-not-key
$a = $items[array_rand($items,1)];
$_SESSION['last_page'] = $a;
include $a;
pokeybit
  • 1,032
  • 11
  • 18
  • 1
    To make sure all pages are visited at least once before the array is reset, use @Philipp Maurer answer below/above – pokeybit Apr 30 '18 at 07:44
  • I tried your code but i get same templates before seeing all of them. It doesn't work as required. –  Apr 30 '18 at 11:28
0

For that to work, you need to save which templates the visitor has already loaded. This can be saved in the session for example:

//At the beginning of your script
session_start();

//... Some code

//Read visited paths from session or create a new list. 
//?? works only in PHP7+. Use isset()?: instead of ?? for previous versions
$visitedTemplates = $_SESSION['visitedTemplates'] ?? [];

//Your list, just slightly changed syntax. Same thing
$originalList = [
    "template1.php",
    "template2.php",
    "template3.php"
];

//Remove all paths that were already visited from the randomList
$randomList = array_diff($originalList, $visitedTemplates);

//You need to check now if there are paths left
if (empty($randomList)) {
    //The user did load all templates

    //So first you set the list to choose a new template from to the list of all templates
    $randomList = $originalList;

    //And then you delete the cache of the visited templates
    $visitedTemplates = [];
}

//Show the user the next one
$randomTemplate = $randomList[array_rand($randomList)];
include $randomTemplate;

//Now we need to save, that the user loaded this template
$visitedTemplates[] = $randomTemplate;

//And we need to save the new list in the session
$_SESSION['visitedTemplates'] = $visitedTemplates;
Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25