Hey guys I'm new to PHP and I wanted to make a page that gets a random word from a text file and here is the code:
<?php
$chosen="Word";
function get(){
$lines= file ("words.txt");
$words=count($lines);
$chosen=$lines[rand(0 ,$words - 1)];
return $chosen;
}
?>
And then I call it from JS:
word = <?php echo json_encode(get()); ?>;
document.getElementById("button").innerHTML = word
The problem I get is the first time the function returns a random word, but after that it's the exact same word over and over.
If PHP is capable of generating your JS code and you prefer to not get messy with AJAX then try this:
index.php
<script>
// Get PHP to create a JS array
var all_words = <?php echo json_encode(file("words.txt")); ?>;
// Create a JS function to fetch a random word
function get_word(){
// Don't go out of bounds and return a word
return all_words[Math.floor((Math.random() * (all_words.length - 1)) + 1)];
}
// Call the function and enjoy :)
document.getElementById("button").innerHTML = get_word();
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.