PHP Foreach If Array Last PHP Foreach If Array Last arrays arrays

PHP Foreach If Array Last


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.


First thing you need to find out what is the last key of the array, and doing so by finding the array length, using the count() function.
Afterwords we gonna create a counter and add +1 on every loop.
If the counter and the last key are equal then it is the last key.

    $last = count($array);    $counter = 1;    foreach ($array as $key => $val){    if ($counter != $last){        // all keys but the last one        // do something            $counter++; // add one to counter count        }        else {            // this is for the last key    }// end else}// end foreach