|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #60684 Add 'last' & 'first' blocks next to 'foreach' block
Submitted: 2012-01-08 06:41 UTC Modified: 2016-12-01 13:33 UTC
Avg. Score:3.0 ± 2.0
Reproduced:1 of 3 (33.3%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: aram_alipoor2010 at yahoo dot com Assigned:
Status: Suspended Package: Scripting Engine problem
PHP Version: 5.4.0RC5 OS: All
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 this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Bug Type:
From: aram_alipoor2010 at yahoo dot com
New email:
PHP Version: OS:


 [2012-01-08 06:41 UTC] aram_alipoor2010 at yahoo dot com
There are a lot of situations that we want our foreach loop act different for first and/or last item. It will be so easy if php add these to concepts as blocks next to foreach. Compiler will run 'first' block for first item, and 'last' block for last item, and normal 'foreach' block for anything in between. The only special case is when array has only one item, in this situation only 'first' block will act. See example at test script.

Test script:
foreach($array as $key => $value)
 $str .= $key . ' = "'.$value.'",';
 $str .= '(' . $key . ' = "'.$value.'",';
 $str .= $key . ' = "'.$value.'")';


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2012-05-05 03:34 UTC] phristen at yahoo dot com
I'm onboard with loop { } else { } construct, but this is an overkill.
I'd much rather have 2 additional array functions: is_array_last(array $array) and is_array_first(array $array)... Of course, I don't insist on these function names, but they should basically return true or false when array pointer is at the first position, or at the last position.
 [2016-06-14 17:53 UTC]
In my opinion, the given use case is doubtful. I might write it as:

$lines = array();
foreach ($array as $key => $value) {
    $lines[] = $key . ' = "' . $value . '"';
$str = '(' . explode(',', $lines) . ')';
 [2016-12-01 13:33 UTC]
-Status: Open +Status: Suspended -Package: Arrays related +Package: Scripting Engine problem
 [2016-12-01 13:33 UTC]
Anyhow, this change would require the RFC process[1], so I'm suspending this feature request for the time being. Note that there had been a similar RFC[2], which had been declined.

[1] <>
[2] <>
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Wed May 18 04:03:41 2022 UTC