Get the Last Index in a PHP Foreach
To get the last element in a PHP foreach statement, get the length of the array using count()
and store that value in a variable. Inside the foreach loop increment the key by one on each iteration and check if the key value is equal to the element count.
$items = ['a','b','c'];
$cnt = count($items);
foreach ($items as $i => $v) {
if (++$i == $cnt) {
print($v);
}
}
c