-1

I want to echo these links as following:

Title
http://www.link.com
Title 2
http://www.link2.com

Instead they come like this:

Title
http://www.link.com
http://www.link2.com
Title2
http://www.link.com
http://www.link2.com

Here is the code that I am using:

    foreach($links as $link ){
    echo $link."<br>";
        foreach($linksx as $linkx ){
    echo $linkx."<br>";
    }
}

Thank you for your help.

2
  • It's because you are looping over the entire $linksx array for each element in $links.
    – gen_Eric
    Apr 18, 2013 at 22:10
  • If $links contains the title and $linkx the url you should have a single 'for' to interact over both lists at same time. Here your second foreach is printing all urls for each title. Apr 18, 2013 at 22:13

3 Answers 3

4

As you have 2 differents arrays, you have to iterate over them on the same time, not one inside the other.

Assuming arrays are indexed numerically (basic array), and have the same size (the same number of elements), you can write

for($i = 0 ; $i < count($links) ; $i++)
{
    echo $links[$i] . "<br />";
    echo $linksx[$i];
}
0
2

It's because you are looping over the entire $linksx array for each element in $links. What you want is to loop over one array then get its counterpart in the other array.

foreach($links as $key=>$link){
    $linkx = $linksx[$key];
    echo $link."<br>".$linkx."<br>";
}
2
  • Woah, thank you exactly what I was looking for, how is there anyway to remove the last output from $links? Apr 18, 2013 at 22:13
  • @user1938320: You mean the trailing <br>?
    – gen_Eric
    Apr 18, 2013 at 22:13
0

Did you mean to nest the loops?

foreach($links as $link )
{
    echo $link."<br>";
}
foreach($linksx as $linkx )
{
    echo $linkx."<br>";
}
1
  • Nope, using your code they come as Title Title2 link.com link2.com I want to output 1 title and 1 link at a time. Thank you for your help Apr 18, 2013 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.