treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Exploding a list of urls...Going insane.

  • Well, I am a front end guy, but I have an interest in everything so i am trying to figure out how to use PHP for some mundane tasks...basically what i want to do is split a list (delimited by a comma) and insert the values of the list into params/attribute in so i only have to copy paste a list once instead of the thousands of urls over and over...Here is where i got stuck:


    <form action="" method="post">
    <label>Links Separated By a COMMA</label>
    <textarea name="urls" cols="" rows=""></textarea>
    <input name="submit" type="submit" value="Submit" />
    </form>
    <?php
    if (isset($_POST['submit'])) {
    $urls = trim($_POST['urls']);
    $arr = explode( ",", $urls);
    $count= count($arr);

    // need to loop through the array here...don't know how...i was thinking a for or while loop..??
    echo '<a href="' . thearrayitem[0] . '>' . thearrayitem[0] . '</a>';
    }
    ?>

    // It should output something like:

    <a href="http://www.link1.com">http://www.link1.com</a&gt;
    <a href="http://www.link2.com">http://www.link2.com</a&gt;
    <a href="http://www.link3.com">http://www.link3.com</a&gt;



    Except "thearrayitem[0]" should be the index as a variable so it can iterate through the items...
    Any help would be much appreciated thanks gin advance!
  • I'm not really a PHP guy either, but to loop through the array wouldn't it be something like this:


    for ($i = 0; $i <= count(thearrayitem); $i++) {
    echo '<a href="' . thearrayitem[i] . '>' . thearrayitem[i] . '</a>';
    }
  • Yes, for some reason I just mixed up the syntax. Thanks a lot @johnnyb
  • Ok, still not working for some reason...

    this is what i have now...im getting an undefined offset error, but $i should be set....unless my loop is failing???


    <form action="" method="post">
    <label>Links Separated By a COMMA</label>
    <textarea name="urls" cols="" rows=""></textarea>
    <input name="submit" type="submit" value="Submit" />
    </form>
    <?php
    if (isset($_POST['submit'])) {
    $urls = trim($_POST['urls']);
    $arr = explode( ",", $urls);
    $count = count($arr);
    for ($i = 0; $i <= $count; $i++) {
    echo '<a href="' . $arr[$i] . '>' . $arr[$i] . '</a>';
    }
    }
    ?>
  • Here is the solution in case any other noobs run into the issue...

    Instead of trying to use the index, simply use a foreach loop and use the value like so:


    if (isset($_POST['submit'])) {
    $urls = trim($_POST['urls']);
    $arr = explode( ",", $urls);
    foreach ($arr as $link) {
    echo '<a href="' . $link . '>' . $link . '</a>';
    }
    }
    ?>