Re: [DISCUSSION] Proposal: Introduce a loop statement
| From: | Larry Garfield | Date: | Tue, 01 Dec 2026 22:07:47 +0000 |
| Subject: | Re: [DISCUSSION] Proposal: Introduce a loop statement | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-133278@lists.php.net to get a copy of this message | ||
On Tue, Dec 1, 2026, at 12:47 PM, Rowan Tommins [IMSoP] wrote:
> On 27/11/2026 20:05, Piotr Ziarek wrote:
>> Hello PHP Internals,
>> I would like to propose introducing a new language construct called loop, designed for
>> executing a block of code a specified number of times.
>>
>
>
> I have some sympathy for this proposal, because I find the C-style for
> loop ugly and fiddly to use; but I agree with others that this is
> perhaps a bit too small a niche for dedicated syntax. Often, even when
> just iterating a fixed number of times, it's useful to have the
> iteration counter available, for things like debug logging or output
> styling (e.g. even/odd).
>
> A more powerful approach would be to combine two new features:
>
> 1) A short-hand for creating a lazy range, e.g. [1..10]. This would
> produce an iterator object that produces sequential numbers, without
> allocating a full array, particularly useful for large and maybe even
> infinite ranges.
>
> 2) The option to omit the "as" clause from a foreach loop, so you can
> loop over an iterable without assigning its output anywhere.
>
> That would allow all of the following:
>
> // Process numbers 1 to 10 inclusive
> foreach([1..10] as $i) {
> doSomethingWithAValue($i);
> }
>
> // Just repeat 10 times
> foreach([1..10]) {
> doSomething();
> }
>
>
> // execute an iterator for a side effect and discard the value
> foreach($someIterator) {
> // do nothing
> }
I concur. A shorthand range would be helpful in many places, and establish a syntax pattern that we
want to use in pattern matching anyway. Allowing the as to be omitted seems like an easy change for
someone interested, as there are already use cases like running out an iterator.
That would obviate the need for a dedicated construct for an edge case.
--Larry Garfield