choose random value only once

安稳与你 提交于 2019-12-12 01:34:58

问题


My page loads a random background image every time it loads:

<?php
    $input = array(1, 2, 3, 4, 5, 6, 7, 8);
    $num = array_rand($input, 1);
    $bg = "img/bg" . $num . ".jpg";
?>

But I want it to do that only once. I want the image to remain the same after a visitor submits a form, for example, thereby reloading the page.

I've tried if($bg=NULL) etc, but to no avail - I guess $bg becomes null again every time the page reloads.

Many thanks in advance!


回答1:


You can use Session variable or cookies if is not set, you choose a background, if is set, you do nothing




回答2:


Got it (thanks to Ricardo):

<?php
    session_start();
    if (!isset($_SESSION['num'])) {
        $input = array(1, 2, 3, 4, 5, 6, 7, 8);
        $_SESSION['num'] = array_rand($input, 1);
    }

    $bg = "img/bg" . $_SESSION['num'] . ".jpg";
?>


来源:https://stackoverflow.com/questions/14429795/choose-random-value-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!