Jump to content

Need help echoing out rand array's


eldan88

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/265537-need-help-echoing-out-rand-arrays/
Share on other sites

<?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];

?>

<?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

<?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)];

 

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.