Yesterday I needed a PHP password generator for the soon to be migrated FileMaker users logins. I found a list of nouns and needed a random picker. A file seemed better than in memory. AI then suggested going to a random byte, then getting the next line which is fast even with large files!
PHP
PHP as Text
function strRandomNoun() {
// Open File
$filePath = PATH_ROOT_XAN . 'data-nouns-2315.txt';
$fileSize = \filesize( $filePath );
$file = \fopen( $filePath, 'r' );
// Loop
do {
// Random Noun
$randomByte = \random_int( 0, $fileSize - 1 );
\fseek( $file, $randomByte );
if ( $randomByte !== 0 ) {
\fgets( $file );
}
$randomLine = \fgets( $file );
$noun = \trim( $randomLine );
} while ( $noun === '' || $noun === false );
// Close File
\fclose( $file );
return $noun;
}