Increment a value inside php foreach?
90,470
Solution 1
No, you will have to use
$i = 0;
foreach ($some as $somekey=>$someval) {
//xyz
$i++;
}
Solution 2
foreach ($some as $somekey=>$someval)
{
$i++;
}
Solution 3
lazy way of doing is:
{
$i=1;
foreach( $rows as $row){
$i+=1;
}
}
,but you have to scope foreach for $i to dont exist after foreach or at last unset it
$i=1;
foreach( $rows as $row){
$i+=1;
}
unset($i);
, but you should use for cycle for that as leopold wrote.
Solution 4
I know it is an old one here, but these are my thoughts to it.
$some = ['foo', 'bar'];
for($i = 0; $i < count($some); $i++){
echo $some[$i];
}
-- Update --
$some = ['foo', 'bar'];
$someCounted = count($some);
for($i = 0; $i < $someCounted; $i++){
echo $some[$i];
}
It would achieve, what you are looking for in first place.
Yet you'd have to increment your index $i.
So it would not save you any typing.
Solution 5
$dataArray = array();
$i = 0;
foreach($_POST as $key => $data) {
if (!empty($data['features'])) {
$dataArray[$i]['feature'] = $data['features'];
$dataArray[$i]['top_id'] = $data['top_id'];
$dataArray[$i]['pro_id'] = $data['pro_id'];
}
$i++;
}
Author by
gvm
Updated on August 03, 2022Comments
-
gvm over 1 year
Is it possible to increment a php variable inside a foreach? I know how to loop by declaring outside.
I'm looking for something like the syntax below
foreach ($some as $somekey=>$someval; $i++) { }