Path: csiph.com!news.mixmin.net!weretis.net!feeder1.news.weretis.net!news.solani.org!.POSTED!not-for-mail From: Thomas 'PointedEars' Lahn Newsgroups: comp.lang.php Subject: Re: break foreach loop after certain iteration and then start it Date: Sat, 05 Mar 2016 02:28:51 +0100 Organization: PointedEars Software (PES) Lines: 67 Message-ID: <2056947.pXOX0CipXs@PointedEars.de> References: <6586983f-c3bc-4eb7-92a3-6035952e8cbb@googlegroups.com> <56D946D4.9030504@arnowelzel.de> Reply-To: Thomas 'PointedEars' Lahn Mime-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 8Bit X-Trace: solani.org 1457141333 8444 eJwNwoERACEIA7CVKEjLOj7K/iP4l2QQbC0mV84PJy3sVk+ysIvCfOzQnUhoilBb+HHZ+H4LjRBy (5 Mar 2016 01:28:53 GMT) X-Complaints-To: abuse@news.solani.org NNTP-Posting-Date: Sat, 5 Mar 2016 01:28:53 +0000 (UTC) User-Agent: KNode/4.14.2 X-User-ID: eJwFwQkBwDAIA0BLtBAeOZQM/xJ2B/XjE+Zww2J1HuMUdKNfMdS9R5bZHJKiF4V8+5kAOW7CEL4r2ZNT9wds4RX2 Cancel-Lock: sha1:AEXYNmwdQCOlFMuGBQy+ikr1EmY= X-NNTP-Posting-Host: eJwNysERACEIA8CWYCSBK0fE9F/C+dvHYtF5MggGBK2Vk8fn0TA11/lG9c6+Ilw1Ftxtso/q/gEiyBGU Xref: csiph.com comp.lang.php:16611 Arno Welzel wrote: > $counter = 0; > > foreach($mylist as $element) ^^ > { > // Do something with $element > > // Add something every three elements > $counter++; > if($counter==3) ^^ Flow control statements should not be written like function calls. > { > echo ''; > $counter = 0; > } > } One does not have to reset the counter if one uses the modulo operator, %, to determine the indexes that are divisible by 3 without remainder. ++$counter; if ($counter % 3 === 0) { … } or if (++$counter % 3 === 0) { … } If the array is not associative and not sparse, the index is implicit and starting from 0, so no counter is needed. 0 is divisible by 3 without remainder, so one has to look for the remainder 2 for the third, sixth etc. element [2 ≡ 1 (mod 3)]: foreach ($mylist as $index => $element) { if ($index % 3 === 2) { … } } Or, if this is too confusing, if (($index + 1) % 3 === 0) { … } > ?> Don’t. -- PointedEars Zend Certified PHP Engineer | Twitter: @PointedEars2 Please do not cc me. / Bitte keine Kopien per E-Mail.