Skip to content
Advertisement

How do I get the last iteration of foreach if the total is unknown

I want to echo a variable at the last iteration of a foreach loop, only counting when a conditional is met inside a loop.

I realize I could echo $var outside the foreach statement, but I’d really like to figure out a way to do this within the foreach statement. This a crude example where that makes total sense, but what I really want to do is figure out the last iteration within the foreach statement.

Here is what I have tried:

$var = "end";
foreach ($options as $option => $icon) {
     if (strpos($check[0], $option) !== false) {            
          echo $icon;
     }
     if (end($options)){
          echo $var;
     }                              
} 

I have also tried setting up a counter when $icon exists but nothing has worked correctly, because the total count is unknown.

How do I do this?

Advertisement

Answer

If the array is not empty, end will always return the last element regardless of what element the array pointer is pointing to.

I don’t see a valid reason for doing this, but you can just see if there is NOT a next element. foreach will advance the array pointer each iteration, so next will attempt to fetch the next one, and if it is on the last element it will fail:

$var = "end";
foreach ($options as $option => $icon) {
     if (strpos($check[0], $option) !== false) {            
          echo $icon;
     }
     if (!next($options)){
          echo $var;
     }                              
} 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement