将相同的随机数写入文件,并根据随机选择显示DIV



我正在向用户显示一个随机数字,我想将该数字保存到一个文本文件中。我的问题是显示的号码和保存的号码不同。我认为这是因为它只是生成两次随机数,而不是将第一个数字(显示给用户的数字(写入文件。

<?php
$min=1;
$max=100;
echo rand($min,$max);
$file = fopen("./randomnumber.txt","a+ n");
fwrite($file,$min,$max);
fclose($file);
?>

我希望显示给用户的数字实际上与写入文件的数字相同。我想显示一个相应的图像,所以如果数字是1,它只回显图像1的转义html,如果2,它是2,依此类推

<?php
$min=1;
$max=100;
echo rand($min,$max);
$file = fopen("./randomnumber.txt","a+ n");
fwrite($file,$min,$max);
fclose($file);
if (rand === '1') {
echo "
<div class='image-1'>
<p>Image 1 Goes Here if 1 is the random number</p>
</div>";
}

else if (rand === '2') {
echo "
<div class='image-2'>
<p>Image 2 Goes Here if 2 is the random number</p>
</div>";
}

else if (rand === '3') {
echo "
<div class='image-3'>
<p>Image 3 Goes Here if 3 is the random number</p>
</div>";
}

else if (rand === '4') {
echo "
<div class='image-4'>
<p>Image 4 Goes Here if 4 is the random number</p>
</div>";
}

else if (rand === '5') {
echo "
<div class='image-5'>
<p>Image 5 Goes Here if 5 is the random number</p>
</div>";
}

// And so on. I need to be able to add new sections for every new image.
// I don't want the full code visible. I only want the DIV of the random selection pushed to the page so it doesn't need to load potentially hundreds of invisible images.


?>

这个想法是生成随机数并将数字保存到一个文件中,但除了显示数字之外,用户必须自己搜索它。我想向用户显示一个基于随机生成的数字的随机DIV,而不加载推送到源代码的每个DIV,因为这可能意味着在我为并且相应地改变最大值。

全面了解我的计划,以便更好地了解这是否是最佳方法。提前谢谢。

问题的出现是因为您调用了两次rand函数。你的逻辑有点错误。要获得与txt文件相同的结果,您需要调用rand一次并将其保存到一个变量中,然后将该变量写入txt文件并将相同的变量回显给用户。

http://sandbox.onlinephpfunctions.com/code/6da31516233da56d852865847bde187443839816

最新更新