There are several ways to get the first and last item in a PHP foreach () loop, and they differ between versions. For PHP 7.3, these are counter (works for all versions), array key first (), and array key last ().