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
someguyhere
Forum Contributor
Posts: 181 Joined: Sun Jul 27, 2008 3:24 pm
Post
by someguyhere » Sun Jul 27, 2008 10:05 pm
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);
Christopher
Site Administrator
Posts: 13596 Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US
Post
by Christopher » Mon Jul 28, 2008 12:27 am
(#10850)
someguyhere
Forum Contributor
Posts: 181 Joined: Sun Jul 27, 2008 3:24 pm
Post
by someguyhere » Mon Jul 28, 2008 9:27 am
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);
Christopher
Site Administrator
Posts: 13596 Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US
Post
by Christopher » Mon Jul 28, 2008 11:22 am
trim()
(#10850)
someguyhere
Forum Contributor
Posts: 181 Joined: Sun Jul 27, 2008 3:24 pm
Post
by someguyhere » Mon Jul 28, 2008 12:54 pm
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);
Christopher
Site Administrator
Posts: 13596 Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US
Post
by Christopher » Mon Jul 28, 2008 12:57 pm
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
Post
by someguyhere » Mon Jul 28, 2008 1:11 pm
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?
onion2k
Jedi Mod
Posts: 5263 Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com
Post
by onion2k » Mon Jul 28, 2008 1:15 pm
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()...