php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #74502 Adding ready variables to foreach
Submitted: 2017-04-26 19:15 UTC Modified: 2017-04-26 19:29 UTC
Votes:1
Avg. Score:1.0 ± 0.0
Reproduced:0 of 1 (0.0%)
From: most dot talebi at gmail dot com Assigned:
Status: Wont fix Package: Variables related
PHP Version: Next Minor Version OS:
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: most dot talebi at gmail dot com
New email:
PHP Version: OS:

 

 [2017-04-26 19:15 UTC] most dot talebi at gmail dot com
Description:
------------
Why PHP does not provide some basic and ready variables for foreach-loops? A variable, for example, for holding the iteration count. Because foreach-loops are an abstract way of looping (than basic for-loop), hence it could be way better to provide at least two (or event one) variables for foreach-loops which updates on every iteration.

Test script:
---------------
For example, the following can save the life of PHP programmers:

foreach($list_of_users as $user) : $i
{
   // the variable of $i updates on every iteration to 
   // reflect the current iteration count
}

Or for more easier programming, a second variable can be added to reflect $is_last status:

foreach($list_of_users as $user) : $i, $is_last
{
   // the variable of $i updates on every iteration to 
   // reflect the current iteration count

   // $is_last is true if the iteration is the last iteration, and is
   // always false for all other previous iterations.
}

// the same case can even be true for $is_first variable




Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-04-26 19:25 UTC] spam2 at rhsoft dot net
frankly you are confusing PHP as programming language with a framework and there is no need to bloat up the core with every thinkable usecase just to save 2 lines of trivial code

is it really that hard even in combiantion with count($list_of_users)

$i = 0;
foreach($list_of_users as $user)
{
 $i++;
}
 [2017-04-26 19:29 UTC] requinix@php.net
-Status: Open +Status: Wont fix
 [2017-04-26 19:29 UTC] requinix@php.net
Why not? Because you can get $i from the iteration key (for simple lists) or two tiny lines of code (as pointed out). Because $is_first is equally trivial to implement. Because $is_last often cannot be determined at all.
Because this is all unnecessary overhead and added complexity for the 9/10 times developers don't need it.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Jan 01 03:01:31 2025 UTC