using the file() function

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
mabufo
Forum Commoner
Posts: 81
Joined: Thu Jul 10, 2003 11:11 pm
Location: Orland Park, IL
Contact:

using the file() function

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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';
}
User avatar
mabufo
Forum Commoner
Posts: 81
Joined: Thu Jul 10, 2003 11:11 pm
Location: Orland Park, IL
Contact:

Post 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:
Post Reply