You are here: Re: Select a random line from a text file « All PHP « IT news, forums, messages
Re: Select a random line from a text file

Posted by MaKroZ on 03/06/06 17:49

On Sun, 05 Mar 2006 20:11:13 -0800, guttyguppy wrote:

> <?php
>
> I did this, and it works. I'm not sure why though, I worked at it for a
> long time and got lucky. Can anyone tell me if they see anything
> inherently wrong with it? It works so hey I'm not complaining...
>
> $fp = fopen('filename.txt', 'r');
> $random = rand() % 3663782;
> fseek($fp, $random);
> if (!fgets($fp)) {
> $data=fgets($fp);
> echo $data;
> }
> else {
> echo fgets($fp);
> }
> ?>

A good solution. Thank NC.
The only thing I can see that if 3663782 is exactly the size of your text
file sometimes your script will produce nothing. It will happen when
rand returns a big number, close to 3663782 enough to fall into the very
last line and then behind it on the second fgets().
So reduce that number by the length of the last line... if you didn't yet,
of course.

--
nn My bookmarks:
(oo) http://www.yakutia.org
| | http://www.theisplist.com
|/\| http://www.tenpieces.com

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация