Newsgroups: php.internals Path: news.php.net Xref: news.php.net php.internals:98572 Return-Path: Mailing-List: contact internals-help@lists.php.net; run by ezmlm Delivered-To: mailing list internals@lists.php.net Received: (qmail 11449 invoked from network); 17 Mar 2017 05:48:46 -0000 Received: from unknown (HELO lists.php.net) (127.0.0.1) by localhost with SMTP; 17 Mar 2017 05:48:46 -0000 Authentication-Results: pb1.pair.com smtp.mail=sebastian@php.net; spf=unknown; sender-id=unknown Authentication-Results: pb1.pair.com header.from=sebastian@php.net; sender-id=unknown Received-SPF: unknown (pb1.pair.com: domain php.net does not designate 188.94.27.5 as permitted sender) X-PHP-List-Original-Sender: sebastian@php.net X-Host-Fingerprint: 188.94.27.5 scarlet.netpirates.net Received: from [188.94.27.5] ([188.94.27.5:45544] helo=scarlet.netpirates.net) by pb1.pair.com (ecelerity 2.1.1.9-wez r(12769M)) with ESMTP id 3B/24-38004-9B87BC85 for ; Fri, 17 Mar 2017 00:48:42 -0500 Received: (qmail 12461 invoked by uid 89); 17 Mar 2017 05:49:52 -0000 Received: by simscan 1.4.0 ppid: 12453, pid: 12456, t: 0.0612s scanners: attach: 1.4.0 clamav: 0.99.1/m:/d:20700 Received: from unknown (HELO ?10.1.55.2?) (php@sebastian-bergmann.de@46.189.67.3) by scarlet.netpirates.net with ESMTPA; 17 Mar 2017 05:49:52 -0000 To: internals@lists.php.net Reply-To: internals@lists.php.net Message-ID: Date: Fri, 17 Mar 2017 06:48:38 +0100 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.8.0 MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit Subject: Let range() return a generator? From: sebastian@php.net (Sebastian Bergmann) For me, foreach (range($low, $high) as $i) is easier to understand than for ($i = 0; $i <= $high; $i++) By easier to understand I do not only mean that the beginning of the loop marked by the foreach/range construct is easier to read. While reading the body of the loop I can be sure that $i is not unexpectedly modified, for instance. Be that as it may, what I would like to propose should be useful for use cases other than the one (see above) that triggered me thinking about this. range() returns an array that contains all elements requested. Depending on the amount of elements, this might not be optimal. One of the most common usages of generators that I have seen is an alternative, userland implementation of the range() function: function xrange($start, $end, $step = 1) { for ($i = $start; $i <= $end; $i += $step) { yield $i; } } This makes me wonder: would there be a benefit in changing the implementation of range() to return a generator instead of an array? And if so, would this constitute a break in backward compatibility?