{"id":1616,"date":"2017-03-22T13:31:06","date_gmt":"2017-03-22T08:01:06","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=1616"},"modified":"2017-03-29T09:58:48","modified_gmt":"2017-03-29T04:28:48","slug":"determine-first-last-iteration-foreach-loop","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/determine-first-last-iteration-foreach-loop\/","title":{"rendered":"PHP &#8211; How to determine the first and last iteration in a for each loop"},"content":{"rendered":"<p><label class=\"label label-Warning\">PROBLEM :<\/label><\/p>\n<h4 id=\"the-question-is-simple-we-have-a-for-each-loop-in-our-code\"><span style=\"color: #800000;\">The question is simple. we have a for each loop in our code:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Php Code<\/span> <\/div> <pre class=\"language-php code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-php code-embed-code\">foreach($array as $element) {<br\/>\/\/code<br\/>}<\/code><\/pre> <\/div>\n<p>In this loop, we want to react differently when we are in first or last iteration.<\/p>\n<p>How to do this?<\/p>\n<p>Php loops for each<\/p>\n<p><label class=\"label label-info\">SOLUTION 1:<\/label><\/p>\n<h4 id=\"use-a-counter\"><span style=\"color: #000000;\">Use a counter:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Php Code<\/span> <\/div> <pre class=\"language-php code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-php code-embed-code\">$i = 0;<br\/>$len = count($array);<br\/>foreach ($array as $item) {<br\/>    if ($i == 0) {<br\/>        \/\/ first<br\/>    } else if ($i == $len - 1) {<br\/>        \/\/ last<br\/>    }<br\/>    \/\/ \u2026<br\/>    $i++;<br\/>}<\/code><\/pre> <\/div>\n<p><label class=\"label label-info\">SOLUTION 2:<\/label><\/p>\n<h4 id=\"another-example\"><span style=\"color: #000000;\">Another example:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Php Code<\/span> <\/div> <pre class=\"language-php code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-php code-embed-code\">$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);<br\/><br\/>foreach ($arr as $a) <br\/>{<br\/><br\/>\/\/ This is the line that does the checking<br\/>if (!each($arr)) echo &quot;End!\\n&quot;;<br\/><br\/>echo $a.&quot;\\n&quot;;<br\/><br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<p><label class=\"label label-info\">SOLUTION 3:<\/label><\/p>\n<h4 id=\"try-this-code\"><span style=\"color: #000000;\">Try this code:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Php Code<\/span> <\/div> <pre class=\"language-php code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-php code-embed-code\">\/\/Store the last key<br\/>$lastkey = key(end($array)); <br\/>foreach($array as $key =&gt; $element) <br\/>{<br\/>    ....do array stuff<br\/>    if ($lastkey === key($array))<br\/>        echo &#039;LAST ELEMENT!&#039;;<br\/>}<\/code><\/pre> <\/div>\n<p><label class=\"label label-info\">SOLUTION 4:<\/label><\/p>\n<h4 id=\"if-your-array-has-unique-array-values-then-determining-the-first-and-last-element-is-trivial\"><span style=\"color: #000000;\">If your array has unique array values, then determining the first and last element is trivial:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Php Code<\/span> <\/div> <pre class=\"language-php code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-php code-embed-code\">foreach($array as $element) {<br\/>    if ($element === reset($array))<br\/>        echo &#039;FIRST ELEMENT!&#039;;<br\/><br\/>    if ($element === end($array))<br\/>        echo &#039;LAST ELEMENT!&#039;;<br\/>}<\/code><\/pre> <\/div>\n<p>This works if last and first elements are appearing just once in an array, otherwise you get false positives. Therefore, you have to compare the keys (they are unique for sure).<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Php Code<\/span> <\/div> <pre class=\"language-php code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-php code-embed-code\">foreach($array as $key =&gt; $element) <br\/>{<br\/>    reset($array);<br\/>    if ($key === key($array))<br\/>        echo &#039;FIRST ELEMENT!&#039;;<br\/><br\/>    end($array);<br\/>    if ($key === key($array))<br\/>        echo &#039;LAST ELEMENT!&#039;;<br\/>}<\/code><\/pre> <\/div>\n<p>Update: Some people are concerned about performance and\/or modifying the array pointer inside a foreach loop.<\/p>\n<p>For those, you can cache the key value before the loop.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Php Code<\/span> <\/div> <pre class=\"language-php code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-php code-embed-code\">reset($array);<br\/>$first = key($array);<br\/>foreach($array as $key =&gt; $element) <br\/>{<br\/>    if ($key === $first)<br\/>        echo &#039;FIRST ELEMENT!&#039;;<br\/>}<\/code><\/pre> <\/div>\n<p><label class=\"label label-info\">SOLUTION 5:<\/label><\/p>\n<p>A more simplified version of the above and presuming you&#8217;re not using custom indexes&#8230;<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Php Code<\/span> <\/div> <pre class=\"language-php code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-php code-embed-code\"><br\/><br\/>$len = count($array);<br\/>foreach ($array as $index =&gt; $item) {<br\/>    if ($index == 0) {<br\/>        \/\/ first<br\/>    } else if ($index == $len - 1) {<br\/>        \/\/ last<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<p><label class=\"label label-info\">SOLUTION 6:<\/label><\/p>\n<p>If you only need just the first element then you may try this code.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Php Code<\/span> <\/div> <pre class=\"language-php code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-php code-embed-code\">$firstElement = true;<br\/><br\/>foreach ($reportData-&gt;result() as $row) <br\/>{<br\/>       if($firstElement) { echo &quot;first element&quot;; $firstElement=false; }<br\/>       \/\/ Other lines of codes here<br\/>}<\/code><\/pre> <\/div>\n","protected":false},"excerpt":{"rendered":"<p>PROBLEM : The question is simple. we have a for each loop in our code: In this loop, we want to react differently when we are in first or last iteration. How to do this? Php loops for each SOLUTION 1: Use a counter: SOLUTION 2: Another example: [ad type=&#8221;banner&#8221;] SOLUTION 3: Try this code: [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[25],"tags":[3319,3320,3321,1204,3318,3326,3323,3325,3322,3324],"class_list":["post-1616","post","type-post","status-publish","format-standard","hentry","category-php","tag-find-the-last-element-of-an-array-while-using-a-foreach-loop-in-php","tag-how-do-i-loop-through-or-enumerate-a-javascript-object","tag-how-do-you-remove-an-array-element-in-a-foreach-loop","tag-how-does-php-foreach-actually-work","tag-how-to-find-the-foreach-index","tag-how-to-make-last-uploaded-images-appear-first-in-foreach-loop","tag-iteration-problems-with-foreach-loop","tag-php-effective-way-to-determine-last-loop-in-foreach","tag-php-how-to-skip-last-element-in-foreach-loop","tag-while-loop-runs-only-in-the-first-iteration-of-foreach-loop"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/1616","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=1616"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/1616\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=1616"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=1616"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=1616"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}