Path: csiph.com!feeder.erje.net!2.eu.feeder.erje.net!ecngs!testfeeder.ecngs.de!81.171.118.63.MISMATCH!peer03.fr7!news.highwinds-media.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Arno Welzel Newsgroups: comp.lang.php Subject: Re: break foreach loop after certain iteration and then start it Date: Sat, 5 Mar 2016 10:52:36 +0100 Lines: 81 Message-ID: <56DAAC64.6010102@arnowelzel.de> References: <6586983f-c3bc-4eb7-92a3-6035952e8cbb@googlegroups.com> <56D946D4.9030504@arnowelzel.de> <2056947.pXOX0CipXs@PointedEars.de> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit X-Trace: individual.net +7Vo2a11NycOzTwbieQNKQUzVGuNw2eaOtfMufioYwih1amTUB Cancel-Lock: sha1:KLRUqJray7exy9lilwJj3gU7r48= In-Reply-To: <2056947.pXOX0CipXs@PointedEars.de> X-Received-Bytes: 2936 X-Received-Body-CRC: 21842433 Xref: csiph.com comp.lang.php:16613 Thomas 'PointedEars' Lahn schrieb am 2016-03-05 um 02:28: > 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. Which is a matter of style. I recognize flow control statements also when they are not formatted with a space preceding the first bracket ;-). But for beginners it may be helpful to distinguish between function calls and flow control. >> { >> 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) > { > … > } Of course one can use modulo as well and use the index of the array in combination with modulo as well. And yes - I know modulo and many other things ;-) But I doubt the OP understands "modulo". I just want to show the basic idea behind it. Finding out what a modulo operator is and that this can make things easier is something the OP should find out on his own - because then it doesn't just copy & paste code he doesn't understand but came to the knowledge by his own experience. [...] > Or, if this is too confusing, > > if (($index + 1) % 3 === 0) You believe this is not confusing for beginners who ask how to achieve the goal to do something every third step of an iteration? This means: 1. You have to understand the syntax of foreach() in this example 2. You have to understand the modulo operator 3. You have to understand why (x+1) % 3 is zero for 0, 2, 5 etc. When someone had enough knowledge to understand all this he would not ask here how to do something every third iteration within a foreach() loop. -- Arno Welzel http://arnowelzel.de http://de-rec-fahrrad.de http://fahrradzukunft.de