Non Repeated Background Images On Refresh or New Page - Array Reset When Empty


At the moment this code is simply picking a random background image from the array and setting it for each new page I navigate. I want a unique background image for each page refresh or each time I click to a new page without the same image being repeated until the array is empty. Currently the array is being reset each time I refresh/navigate and I am seeing some repeated backgrounds before all images in the array have been ‘used’. The array should reset only after all 7 backgrounds have been uniquely sampled. The location of my code is up the top of my ‘head’ html file which is being used across all pages using php ‘includes’. I’m thinking I must need to use a session but Im not sure. Any help please?

$backgrounds = $background_history = array(‘one.jpg’, ‘two.jpg’, ‘three.jpg’, ‘four.jpg’, ‘five.jpg’, ‘six.jpg’, ‘seven.jpg’);

$result = “”;
for ($i = 1; $i < 8; $i++) {
if (empty($background_history)) {
$background_history = $backgrounds;
$key = array_rand($background_history, 1);
$selected = $background_history[$key];
$result = $selected;

    .all-backgrounds {
        background: linear-gradient(rgba(0, 0, 0, 0.45), rgba(0, 0, 0, 0.45)), url(../static/backgrounds/<?php echo $result ?>) no-repeat center center;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        background-size: cover;
        -o-background-size: cover;
        height: 100%;



You need to save the state of the array. The server is stateless and looses and rebuilds the array each time it is called.
So, if for example you saved the array to the session, you could pop the used keys out and still maintain the current state of the new array each time.


Thanks for your comment but I still can’t get it working. I created a session array but still seeing duplicated backgrounds before the array is empty and reset.

I would have thought the array state is stored between each request now but still no go.

$backgrounds = $background_history = array(‘one.jpg’, ‘two.jpg’, ‘three.jpg’, ‘four.jpg’, ‘five.jpg’, ‘six.jpg’, ‘seven.jpg’);

$_SESSION[‘history’] = $background_history;

$result = “”;
for ($i = 1; $i < 8; $i++) {
if (empty($_SESSION[‘history’])) {
$_SESSION[‘history’] = $backgrounds;

$key = array_rand($_SESSION['history'], 1);
$selected = $_SESSION['history'][$key];
$result = $selected;



You are still setting the array regardless. Do an experiment.

[php] <?php
if( isset( $_SESSION[‘history’] )) {
} else {
$_SESSION[‘history’] = array(‘one.jpg’, ‘two.jpg’, ‘three.jpg’, ‘four.jpg’, ‘five.jpg’, ‘six.jpg’, ‘seven.jpg’);

// put it in a function so we only have to modify one piece of code
function getImage($ar) {
$key = array_rand($ar, 1);
$selected = $ar[$key];
echo $selected;
return $ar;