Page 1 of 1

using the file() function

Posted: Wed Jul 05, 2006 1:29 pm
by mabufo
I made a simple script that will get a random quote from an array and display the quotes randomly when the page is loaded. It works great. However, as the list of quotes grows, so will the amount of code. So what I wanted to do was load all of the quotes into a simple flat file and read them fromthe file into an array. Simple right? Well I'm having problems.

For debugging purposes, the code does not randomize the gathered array, it will instead temporarily output every array element.

Code: Select all

<?php 
	$quotes = file('quotes.txt');
		$numberOfQuotes = count($quotes);
		
		if($numberOfQuotes == 0){

			echo 'Problem loading quote.';
			
			}
		
		else{
			for ($x = 0; $x <= $numberOfQuotes; $x++)  {
  
				echo $quotes[x];

				}
			}		

	?>
It is my understanding that $quotes will become an array that holds each line of text in the file 'quotes.txt'. My first question is about error handling. How can I be sure that the array has been created properly? Is my method good enough? Would it work? What is a more efficient way to make sure that the file() function was executed properly? I'm going to be honest though, I set it up like that so I could use the $numberOfQuotes variable inside the for loop. So I guess it works out, eh?

Secondly, why is it that I am not getting any output from my for loop? I have one line in the 'quotes.txt' file - so the $quotes array has to contain something, right? My guess is that the file() function is not working like I think it should... but of course, I'm at a loss as to how to get it going correctly.

Posted: Wed Jul 05, 2006 1:42 pm
by John Cartwright
try this

Code: Select all

$file = file('quotes.txt');

if ($file != false)
{
   $count = count($file);
   if ($count > 0)
   {
      shuffle($file);
      echo $file[0];
   }
   else
   {
       echo 'File empty';
   }
}
else
{
   echo 'Failed opening file';
}

Posted: Wed Jul 05, 2006 1:55 pm
by mabufo
That works lovely. I sure hope I can retain what I learn from your logic. 8)

Though I would think that the sort of logic you put into your code is gained from situations identical to this... :lol: