Re: RFC - Array slice syntactic sugar

From: Date: Fri, 20 Mar 2015 21:28:15 +0000
Subject: Re: RFC - Array slice syntactic sugar
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to internals+get-85335@lists.php.net to get a copy of this message
Alex Bowers wrote: > Anywhere on the front-end where a foreach() is used, and expects at most > say, 10 items. But the full dataset is fetched back (to show a summary > after the first 10 or whatever other reason). > > The old code would have required a counter, the new code does not. This > would make it cleaner for the front-end developer to understand. > > <?php > $results = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; > > // Old > $count = 0; > > foreach($results as $result){ > if($count++ > 9) break; > echo $result . "\n"; // 1 2 3 4 5 6 7 8 9 > } > > // New > > foreach($results[*:9] as $result) { > echo $result . "\n"; // 1 2 3 4 5 6 7 8 9 > } // alternative old foreach(array_slice($results, 0, 9) as $result) { echo $result . "\n"; // 1 2 3 4 5 6 7 8 9 } Not so bad, in my opinion. -- Christoph M. Becker

« previous php.internals (#85335) next »