|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[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.'")';
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Nov 05 23:00:01 2025 UTC |
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.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) . ')'; ?>