Possible Duplicate:
How to get random value out of an array
I have code applying a random font to a div of text which is taken from the last 20 lines of a .txt file. I would like to apply a different random 开发者_运维百科font to each line... any pointers?
<?php
$fonts = array("Helvetica", "Arial", "Courier", "Georgia", "Serif", "Comic Sans", "Tahoma");
shuffle($fonts);
$randomFont = array_shift($fonts);
$output = "";
$lines = array_slice(file("users.txt"), -20, 20);
foreach ( $lines as $line )
{
$output .= '<div style="font-family:' . $randomFont . '; margin-left: ' . rand(0, 60) . '%; opacity: 0.8;">' . $line . '</div>';
}
echo $output;
?>
Live demo here.
The code:
$fonts = array("Helvetica", "Arial", "Courier", "Georgia", "Serif", "Comic Sans", "Tahoma");
shuffle($fonts);
$output = "";
$lines = array();
for($i = 0; $i < 40; $i++) $lines[] = "line $i";
$i = 0;
foreach ( $lines as $line ) {
if($i == count($fonts)) {
shuffle($fonts);
$i = 0;
}
$output .= '<div style="font-family:' . $fonts[$i] . '; margin-left: ' . rand(0, 60) . '%; opacity: 0.8;">' . $line . "</div>\n";
$i++;
}
echo $output;
Randomize your fonts:
$Random = $fonts[rand(0, count($fonts) - 1)];
Been thinking about it and have a simpler solution.
<?php
$fonts = array ('font 1', 'font 2', 'font 3'); // 20 entries for the full set
shuffle ($fonts);
while ($font = array_pop ($fonts))
{
$output .= '<div style="font-family:' . $font . ';"></div>';
}
?>
This is obviously not an exact solution to the problem you posted above, and it's not intended to be. It's intended to provide an example of an approach for getting random values that are guaranteed to be unique. You should be able to incorporate the idea expressed here into your own code without too much difficulty.
精彩评论