Reputation: 105
I found this random page script which is in PHP file. I'm a bit frustrated that it's hard to refresh the page when I click on refresh (reload) on the browser. Each random page has an article and some have two images but mostly one image. There is only 3 articles.
The issue is that it takes 2 or 3 clicks in order to refresh the page. There's No button, it only refreshed the page when you click 'reload' the page on the browser (all browser) or visit to the site. In order for it to work it does always take at least 2 or 3 clicks to refreshed.
Here is the code:
<?php
$pagesArray = array("article1.php", "article2.php", "article3.php");
$randNum = rand(0, count($pagesArray)-1);
echo $pagesArray[$randNum];
?>
I also try modify the script to used "shuffle"
<?php
$pagesArray = array("article1.php", "article2.php", "article3.php");
shuffle($pagesArray);
echo $pagesArray[0];
?>
and also to used "array_rand"
<?php
$pagesArray = array("article1.php", "article2.php", "article3.php");
array_rand($pagesArray);
echo $pagesArray[0];
?>
Is there a way to make the code better? I just want the code to refresh the different pages rather clicking 2 or 3 times for it to work. I appreciate any suggestion how to make it works correctly or any example would be appreciate for me to see the full picture!
Thanks
Upvotes: 0
Views: 281
Reputation: 14747
I'm not familiar with PHP, but if you're asking which method of selecting a random element in your array is fastest, I would guess that is option 1. Generating a random integer takes constant time, and returning an element of an array by the array index should take constant time as well. I don't know how shuffle is implemented, but I'm pretty sure getting a random number would take less time than shuffling an array of elements. Whatever the case, there shouldn't be a noticeable difference to the user if you only have a few elements in your array.
As for why it takes 2 or 3 refreshes for it to "work", I'm guessing that is probably because you're just returning the same page multiple times. If you can get what page the user is currently on (or has visited), you can just remove the item from the array before picking one.
Upvotes: 3