foreach( $tabs2 as $tab2 => $name ){
    $class = ( $tab2 == $current ) ? ' current' : '';
    echo("<li class='posts'><a href='?page=pigg&tab=help&tab2=$tab2' class='$class'>$name");
    echo(' |'); // If array last then do not display
    echo('</a></li>');
}

I'm using a foreach loop to create a navigation for a WordPress plugin I'm working on, but I don't want the ' |' to be displayed for the last element, the code above is what I've got so far, I was thinking of using an if statement on the commented line, but not sure what the best approach would be, any ideas? Thanks!

share|improve this question
You can move the 2nd and 3rd echo above the first one. Then if (iteration== first_time) "do_not_echo_2nd,3rd". – Neal Mar 14 '12 at 10:30

3 Answers

The end() function is what you need:

if(end($tabs2) !== $name){
    echo ' |'; // not the last element
}
share|improve this answer
Thank you, this worked perfectly, I'll accept this as the answer, but I got to wait 3 minutes. xD – Kristian Matthews Mar 14 '12 at 10:34

I find it easier to check for first, rather than last. So I'd do it this way instead.

$first = true;
foreach( $tabs2 as $tab2 => $name ){
    if ($first) {
      $first = false;
    } else {
      echo(' | ');
    }
    $class = ( $tab2 == $current ) ? ' current' : '';
    echo("<li class='posts'><a href='?page=pigg&tab=help&tab2=$tab2' class='$class'>$name</a></li>");
}

I also combined the last two echos together.

share|improve this answer
Thanks for the help, but this just immediately sets $first = true; then $first = false; essentially. – Kristian Matthews Mar 14 '12 at 10:31
Hm, that's surprising -- it doesn't only echo out the break at the beginning of each non-first line? – Waynn Lue Mar 14 '12 at 17:42

Something like this is possible:

$size = count($tabs2);
$counter = 0;
foreach( $tabs2 as $tab2 => $name ){
    $class = ( $tab2 == $current ) ? ' current' : '';
    echo("<li class='posts'><a href='?page=pigg&tab=help&tab2=$tab2' class='$class'>$name");
    if ( ++$counter < $size ){
        echo(' |'); // If array last then do not display     
    }
    echo('</a></li>');
}
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

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