You are here: Re: Select random files out of a directory « PHP Programming Language « IT news, forums, messages
Re: Select random files out of a directory

Posted by Stefan Rybacki on 01/05/07 16:23

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Curtis schrieb:
> $dir = './';
> $files = array();
> $file = '';
> if ( is_dir($dir) ) {
> if ( $d = opendir($dir) ) {
> while ( ($file = readdir($d)) !== false ) {
> if ( !is_dir($file) ) $files[] = $file;
> }
> }
> }
>
> // specify an int for the optional 2nd arg if you
> // need more than one random file
> $randomKeys = array_rand($files);
> $randomFile = $files[$randomKeys[0]];
>
>
Without the memory overhead selecting one random file could in addition
look like this then:

$dir = './';
$file = '';
mt_srand(time());
$probability=mt_getrandmax()/10000;
if ( is_dir($dir) ) {
if ( $d = opendir($dir) ) {
while ( ($file = readdir($d)) !== false ) {
if ( !is_dir($file) ) {
if (mt_rand()<$probability) break;
}
}
}
}

I know it's far from perfect and it's not equally distributed but might
save some execution time if you accidently select the second file ;) as
well as you don't have the memory overhead and it takes at most as long
as the original script. Important here is the probability variable,
which should be adjusted with an estimated file count of the desired folder.

Stefan
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.1 (MingW32)

iD8DBQFFnnuRyeCLzp/JKjARAgImAJ0WdU9IjvrF9+vgYqRGQk3ewvjW/ACfcrAx
i7zjE6lnU58u6SsykMualQs=
=4QPJ
-----END PGP SIGNATURE-----

 

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

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