creating array from file?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

creating array from file?

Post 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);
 
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: creating array from file?

Post by Christopher »

(#10850)
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

Re: creating array from file?

Post 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);
 
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: creating array from file?

Post by Christopher »

trim()
(#10850)
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

Re: creating array from file?

Post 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);
 
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: creating array from file?

Post 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().
(#10850)
someguyhere
Forum Contributor
Posts: 181
Joined: Sun Jul 27, 2008 3:24 pm

Re: creating array from file?

Post 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?
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: creating array from file?

Post 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()...
Post Reply