News:

Bored?  Looking to kill some time?  Want to chat with other SMF users?  Join us in IRC chat or Discord

Main Menu

text list to array

Started by Anguz, August 18, 2003, 04:45:55 AM

Previous topic - Next topic

Anguz

if I have a text with urls, one per line, how can they be put into an array?

Cristián Lávaque http://cristianlavaque.com

horus

I usually use "explode",

explode ( string separator, string string [, int limit]))

checkout php.net [nofollow]

Metho

This'll go right off the text file, auto put into an array based off of endlines. Very easy. And yes, php.net is your friend.
myurls.txt
----------------
http://www.simplemachines.org
http://www.yabbse.org
http://www.php.net
http://www.google.com
---------------------

<?PHP
$urlarray = file ('myurls.txt');
echo "$urlarray[2]";
?>


Will return http://www.php.net. Neato, huh? :D

Methonis
Joshua "Methonis" Frazer
Support Specialist
The Simple Machines Team

Anguz

#3
QuoteI usually use "explode",
I was thinking about that, but wasn't sure how

QuoteThis'll go right off the text file, auto put into an array based off of endlines
sweet! I didn't know the file() function!

http://mx2.php.net/manual/en/function.file.php
it says there that the newline is kept at the end of each value of the array... so if I want to use the url in a link, I should trim() it, right? like:

echo '<a href="' . trim($urlarray['2']) . '">php.net</a>';
Cristián Lávaque http://cristianlavaque.com

Anguz

#4
hmm... what if the text is in a variable because it was retrieved from the db? like:

$urlarray = file($myurls);

the name of the function doesn't suggest it would work, that's why I ask...

if it doesn't, then, is there a function like this one that'd work with a variable? or would I have to go with explode()?
Cristián Lávaque http://cristianlavaque.com

Metho

Well, with that trim thing, I tested it, and I don't get the newline return attached...so it might depend on php version, not sure.

Anyhow, if you've already got all of the url's in a VARIABLE, then yes, do an explode. When you said text I assumed you meant a text file. You'd do something like:

$urlarray = explode("\n", $myurls)

Methonis
Joshua "Methonis" Frazer
Support Specialist
The Simple Machines Team

Anguz

thank you guys for your great help  ;)
Cristián Lávaque http://cristianlavaque.com

Advertisement: