Forum Moderators: coopster

Message Too Old, No Replies

Multiple random lines from text file

         

encyclo

7:56 pm on Mar 30, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm hoping some of you experts can help me with this: I have a text file with HTML fragments, one on each line. I want to display 4 of these lines, in a random order, with no repetition. Here's what I have so far:

<?php 
$filename = $_SERVER["DOCUMENT_ROOT"].'/inc/pub/pub_array.inc';
if ($fileContents = file_get_contents($filename)) {
$contentsArray = explode("\n", $fileContents);

$numLines = count($contentsArray)-1; 
print($contentsArray[rand(0,$numLines)] . "\n"); // 1
print($contentsArray[rand(0,$numLines)] . "\n"); // 2
print($contentsArray[rand(0,$numLines)] . "\n"); // 3
print($contentsArray[rand(0,$numLines)] . "\n"); // 4
}
else {
die('Could not get contents of: ' . $filename);
}
?>

This provides the randomness, but there are repeating entries - in other words, some lines from the text file are shown twice or more. I've looked at the PHP function

array_rand
, but I don't know whether it would do the trick, or how to adapt it...

Anyone have any ideas?

Many thanks for your help!

Added: I'm using PHP 4.3.4

coopster

12:07 am on Mar 31, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



shuffle [php.net] may give you what you want -- random lines but not repeats. And, first off, let's get rid of an extra step. The PHP file() [php.net] function will return the results in an array for you. No need to explode on the newlines:
<?php  
$filename = $_SERVER["DOCUMENT_ROOT"].'/inc/pub/pub_array.inc';
$how_many_to_show = 4;
if ($fileContents = file($filename)) {
shuffle($fileContents);
for ($i = 0; $i < $how_many_to_show; $i++) {
print($fileContents[$i]. '<br />');
}
} else {
die('Could not get contents of: ' . $filename);
}
?>

encyclo

12:49 am on Mar 31, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



coopster - you are a genius! Works perfectly!

Thank you so much! I promise I'll contribute more when I understand this PHP thing better... ;)

encyclo

coopster

1:05 pm on Mar 31, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Genius? (smiles...blushes...humbles himself before replying) ...Thank You.

>>I promise I'll contribute more when I understand this PHP thing better...

We'll hold you to that :)