Reputation: 934
I'm displaying a random number to a user and I want to save that number to a text file. My problem is that the number being shown and the number being saved is different. I assume this is because it's just generating a random number twice rather than writing the first number (the one being shown to the user) to the file.
<?php
$min=1;
$max=100;
echo rand($min,$max);
$file = fopen("./randomnumber.txt","a+ \n");
fwrite($file,$min,$max);
fclose($file);
?>
I'd like the number shown to the user to actually be the same number written to the file. I'm wanting to show a corresponding image so if the number is 1 it echoes only the escaped html for image 1, if 2 it's 2 and so on.
<?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.
?>
The idea is to generate the random number and save the number to a file but beyond just showing the number so the user has to search for it themselves I'd want to show the user a random DIV based on the randomly generated number without loading every DIV being pushed to the source code because this could potentially mean hundreds of images need to be loaded as I'd add a new html section for each and change the max value accordingly.
Providing a full view of what I'm planning to give a better context as to if this is the best approach. Thanks in advance.
Upvotes: 0
Views: 73
Reputation: 110
The problem comes because you are calling rand function twice. Your logic is a bit wrong here. To get to txt file same result you need to call rand once and save it to a variable and then write that variable to txt file and echo the same variable to user.
http://sandbox.onlinephpfunctions.com/code/6da31516233da56d852865847bde187443839816
Upvotes: 1