Jump to content

[SOLVED] Separate looped foreach() variables with special characters?


bloodgoat

Recommended Posts

Say this is my navigation array:

<?php
$navigation = array();
$navigation[] = array("Page 1", "URL 1");
$navigation[] = array("Page 2", "URL 2");
$navigation[] = array("Page 3", "URL 3");
?>

Got it? Awesome.

Now suppose I'm using a foreach() loop to display them.

<?php
foreach($navigation as $link){
$links .= "<a href=\"".$link[1]."\">$link[0]</a> ";
}
?>

Alright, now when I post "$links" on my page, it displays them as:

Page 1 Page 2 Page 3

 

It's legible if you're not a moron, but still... I think it would look a bit nicer if it looked something like this:

Page 1 | Page 2 | Page 3

 

I realize I could separate them by looping them with <td> and putting them each in their own column, but I don't have THAT much room to work with in the column they're being inserted to, and I don't want to stretch out my page or anything. So how do I do what I mentioned above?

 

Obviously I could just loop them like

$links .= "<a href=\"".$link[1]."\">$link[0]</a> | ";

but that means even the last link would have the stick at the end which just isn't acceptable. Enlighten me?

This will work:

 

$k = 1;
foreach($navigation as $link){
   if ($k!=1){$links .=  ' | ';}
   $links .= "<a href=\"".$link[1]."\">$link[0]</a>";
   $k++;
}

 

Basically all of the ones except the first in the loop will output | before them

When you echo out $links, remove the last 3 characters from the string with substr, example

 

foreach($navigation as $link){
   $links .= "<a href=\"".$link[1]."\">$link[0]</a> | ";
}

$links = substr($lines, 0, -3);

echo $links;

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.