简体   繁体   中英

PHP foreach echoing strings

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.

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];
}

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>";
}

Did you mean to nest the loops?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM