php.net |  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
Votes:6
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
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please — but make sure to vote on the bug!
Your email address:
MUST BE VALID
Solve the problem:
43 - 17 = ?
Subscribe to this entry?

 
 [2012-01-08 06:41 UTC] aram_alipoor2010 at yahoo dot com
Description:
------------
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.'",';
}
first
{
 $str .= '(' . $key . ' = "'.$value.'",';
}
last
{
 $str .= $key . ' = "'.$value.'")';
}


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

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] cmb@php.net
In my opinion, the given use case is doubtful. I might write it as:

<?php
$lines = array();
foreach ($array as $key => $value) {
    $lines[] = $key . ' = "' . $value . '"';
}
$str = '(' . explode(',', $lines) . ')';
?>
 [2016-12-01 13:33 UTC] cmb@php.net
-Status: Open +Status: Suspended -Package: Arrays related +Package: Scripting Engine problem
 [2016-12-01 13:33 UTC] cmb@php.net
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] <https://wiki.php.net/rfc/howto>
[2] <https://wiki.php.net/rfc/loop_or>
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 18:01:29 2024 UTC