Sumber : https://www.w3docs.com/snippets/php/how-to-determine-the-first-and-last-iteration-in-a-foreach-loop.html#:~:text=A%20handy%20solution%20to%20determining,)%20%7B%20%2F%2F%20last%20%7D%20%2F%2F%20%E2%80%A6
<?php
$i = 0;
$len = count($array);
foreach ($array as $item) {
if ($i == 0) {
// first
} elseif ($i == $len - 1) {
// last
}
// …
$i++;
}
?>