Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

php - keep value that is shuffled even if page is refreshed

I made a quiz that generates a random answer at the end by using the shuffle() function. I want it to stay on the same answer and not to shuffle again.

My code:

<?php

//Array of cars
$answer = array(
"Mercedes", 
"Benz", 
"Honda", 
"Toyota", 
"Nissan", 
"Mazda", 
"Hyundai", 
"Ford", 
"Lexus", 
"Lamborghini", 
"Ferrari", 
"Porche", 
"Mitsubushi", 
"Scion", 
"Chrysler", 
"Jeep", 
"Masarati"
);

// Shuffle the order
shuffle($answer);

echo $answer[0];
?>

For example: if $answer was shuffled and generated "Mitsubushi" --- when I refresh the page it should stay "Mitsubushi" but what happens is that when the page is refreshed it reshuffles again.

So when I refresh the page, it echo's another thing do the shuffle() function.

image

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Store the array into a session variable

    <?php
    session_start();

    //Array of cars
    $answer = array(
    "Mercedes", 
    "Benz", 
    "Honda", 
    "Toyota", 
    "Nissan", 
    "Mazda", 
    "Hyundai", 
    "Ford", 
    "Lexus", 
    "Lamborghini", 
    "Ferrari", 
    "Porche", 
    "Mitsubushi", 
    "Scion", 
    "Chrysler", 
    "Jeep", 
    "Masarati"
    );

    // Shuffle the order only first time
   if(!isset($_SESSION['shuffle_answer'])){
      $_SESSION['shuffle_answer']=shuffle($answer);
   }

    if(isset($_SESSION['shuffle_answer'])){
       echo $_SESSION['shuffle_answer'][0];
    }else{
       echo $answer[0];
    }
    ?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...