Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Foreach If Array Last

Tags:

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!

like image 248
Kristian Matthews Avatar asked Mar 14 '12 10:03

Kristian Matthews


People also ask

How to check if last element in foreach PHP?

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.

How to get last array from foreach loop in PHP?

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.

How do you find the last loop in foreach?

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.

How foreach works in PHP?

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.


2 Answers

The end() function is what you need:

if(end($tabs2) !== $name){
    echo ' |'; // not the last element
}
like image 116
Yeroon Avatar answered Oct 25 '22 12:10

Yeroon


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.

like image 33
Waynn Lue Avatar answered Oct 25 '22 11:10

Waynn Lue