Page 1 of 1

creating array from file?

Posted: Sun Jul 27, 2008 10:05 pm
by someguyhere
How would I modify the following code to pull the array from a file instead of being hard coded into the document?

Code: Select all

srand((float) microtime() * 100000);
$input1 = array("ex1", "ex2", "ex3", "ex4");
$rand_key1 = array_rand($input1);
 

Re: creating array from file?

Posted: Mon Jul 28, 2008 12:27 am
by Christopher

Re: creating array from file?

Posted: Mon Jul 28, 2008 9:27 am
by someguyhere
Awesome, thanks!

How do I strip out the line endings? When I look at the output, each item pulled into the array starts on a new line. Here is what I am using:

Code: Select all

srand((float) microtime() * 100000);
$input1 = file('file.txt');
$rand_key1 = array_rand($input1);
 

Re: creating array from file?

Posted: Mon Jul 28, 2008 11:22 am
by Christopher
trim()

Re: creating array from file?

Posted: Mon Jul 28, 2008 12:54 pm
by someguyhere
I solved it just a little bit before you posted but your slution is different than mine. Is one any better than the other?

Code: Select all

srand((float) microtime() * 100000);
$input1 = file('data/file.txt');
$input1 = str_replace("\n", "", $input1);
$rand_key1 = array_rand($input1);
 

Re: creating array from file?

Posted: Mon Jul 28, 2008 12:57 pm
by Christopher
str_replace("\n", "", $input1); removes just the newline character; trim() removes all whitespace. It simply depends on which you want. There is also ltrim() and rtrim().

Re: creating array from file?

Posted: Mon Jul 28, 2008 1:11 pm
by someguyhere
Ahh...ok.

In this case there are spaces within the words that must remain, so the way I have it coded is the best for this situation?

Re: creating array from file?

Posted: Mon Jul 28, 2008 1:15 pm
by onion2k
someguyhere wrote:In this case there are spaces within the words that must remain, so the way I have it coded is the best for this situation?
Someone didn't bother to read the PHP manual page for trim()...