Need Some PHP Experts Up Hurr

whatshisname

Junior Member
Joined
Jan 17, 2011
Messages
144
Reaction score
120
OK So I have a problem. What I want to do is this

I have a bunch of URLS in a .txt file. I want to randomly pull them out and insert them into my javascript

How will I do this? Sorry I am a php noob here and just started. Thanks
 
Not sure 100% what you want but think

1) read textfile (urls) into array
2) loop through array echoing them to out put along with html and Jscript

PM me I may have time to write some thing
 
1)read texfile (urls) into array
2) use shuffle function and shuffle the array. The get lines secuentialy with a loop.
 
How many URLs are you talking here? I agree that an array is probably the best data structure to use, as it would allow you to have very fast data retrieval...depending on the size or if the number of urls will vary, you may want to look into the best way to create the array, as you don't want to be having your arrays continually copy themselves over into new memory locations.
 
untested:
Code:
	$array = file('textfile.txt');
	$lines = count($array);
	$randomurl = $array[rand(1,$lines)];

so $array is your text file read into an array
$lines gets the number of lines in the textfile
$randomurl is one of the values in the array (decided by a random number between 1 and the number of lines)
 
PHP:
// get file into array (fine for about 10k lines or less then it starts hogging RAM)
$urls = file("urls.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// randomly select url from the array and trim any blank space
$url = trim($urls[rand(0,count($urls)-1)]);

// self explanitory
echo $url;

eskimo's code didn't take into account that arrays start at 0, not 1. also the way his code is used, as i said, would skip the 1st line and would be turning up a blank line as count() returns the amount of items in the array. so starting at 0, you need to take the count minus 1.

the only flaw in snickers' code is the overall speed of it (if this matters to you). the array_rand() function is slower than using rand(). though it's minimal, the results of a benchmark test can be seen here: http://www.ebrueggeman.com/article_php_benchmarking_rand.php

in my code, using the trim() function probably isn't needed, and in most cases, the parameters i've set when reading the file into an array might be overboard. but both bits of code will eliminate some potential errors later...

for simplicity, accuracy, and speed... use my code.
 
Back
Top