0

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;
?> 
Community
  • 1
  • 1
Jay
  • 902
  • 2
  • 12
  • 27

3 Answers3

1

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;
Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127
0

Randomize your fonts:

$Random = $fonts[rand(0, count($fonts) - 1)];
tradyblix
  • 7,439
  • 3
  • 25
  • 29
0

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.

GordonM
  • 31,179
  • 15
  • 87
  • 129