eldan88 Posted July 11, 2012 Share Posted July 11, 2012 Hi, I have a website which I would like to echo out random cool facts everytime a page loads. How can I use the random array to to this... this is what i have done below so far $facts = array ("One out of 20 people have an extra rib ", "44% of kids watch television before they go to sleep" ); Thanks Quote Link to comment Share on other sites More sharing options...
xyph Posted July 11, 2012 Share Posted July 11, 2012 <?php $facts = array ("One out of 20 people have an extra rib ", "44% of kids watch television before they go to sleep" ); // method 1 $size = count($facts)-1; $rand = rand(0,$size); echo $facts[$rand]; // method 2 shuffle($facts); echo $facts[0]; ?> Quote Link to comment Share on other sites More sharing options...
eldan88 Posted July 11, 2012 Author Share Posted July 11, 2012 <?php $facts = array ("One out of 20 people have an extra rib ", "44% of kids watch television before they go to sleep" ); // method 1 $size = count($facts)-1; $rand = rand(0,$size); echo $facts[$rand]; // method 2 shuffle($facts); echo $facts[0]; ?> Method 2 worked thank you so much! I have a question though.. just out of curiosity, why is there a "-1" for $size = count($facts)-1; Thanks Quote Link to comment Share on other sites More sharing options...
xyph Posted July 11, 2012 Share Posted July 11, 2012 Because array indexes start at 0... So if your array had 10 entries, their keys would range from 0 to 9. Does that help? Quote Link to comment Share on other sites More sharing options...
Barand Posted July 11, 2012 Share Posted July 11, 2012 <?php $facts = array ("One out of 20 people have an extra rib ", "44% of kids watch television before they go to sleep" ); // method 1 $size = count($facts)-1; $rand = rand(0,$size); echo $facts[$rand]; // method 2 shuffle($facts); echo $facts[0]; ?> // method 3 echo $facts[array_rand($facts)]; Quote Link to comment Share on other sites More sharing options...
xyph Posted July 11, 2012 Share Posted July 11, 2012 Show off. ... knew I missed an easy one. Quote Link to comment Share on other sites More sharing options...
eldan88 Posted July 15, 2012 Author Share Posted July 15, 2012 I Get it! Because you where using the count function! Thank you so much!!!! <?php $facts = array ("One out of 20 people have an extra rib ", "44% of kids watch television before they go to sleep" ); // method 1 $size = count($facts)-1; $rand = rand(0,$size); echo $facts[$rand]; // method 2 shuffle($facts); echo $facts[0]; ?> Method 2 worked thank you so much! I have a question though.. just out of curiosity, why is there a "-1" for $size = count($facts)-1; Thanks Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.