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!
you can do a count(). or if you're looking for ONLY the last element, you can use end(). end(arr); returns only the last element.
Use Counter in PHP foreach Loop Use count() to determine the total length of an array. The iteration of the counter was placed at the bottom of the foreach() loop - $x++; to execute the condition to get the first item. To get the last item, check if the $x is equal to the total length of the array.
Method 1: It is the naive method inside foreach loop to find iteration. Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.
PHP foreach loop is utilized for looping through the values of an array. It loops over the array, and each value for the fresh array element is assigned to value, and the array pointer is progressed by one to go the following element in the array.
The end()
function is what you need:
if(end($tabs2) !== $name){
echo ' |'; // not the last element
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With