Increase value inside php foreach?

Is it possible to increase the php variable inside foreach? I know how to loop, announcing outside.

I am looking for something like the syntax below

foreach ($some as $somekey=>$someval; $i++) { } 
+4
source share
9 answers

No, you will need to use

 $i = 0; foreach ($some as $somekey=>$someval) { //xyz $i++; } 
+28
source
 foreach ($some as $somekey=>$someval) { $i++; } 
+5
source

I know that here is old, but these are my thoughts.

 $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]; } 

He would achieve what you are looking for in the first place.
However, you need to increase your $ i index.
So this will not save you from entering text.

+1
source

Is there a reason not to use

 foreach ($some as $somekey=>$someval) { $i++; } 

?

0
source
 foreach ($some as $somekey=>$someval) { $i++; } 
0
source
 foreach ($some as $somekey=>$someval) { $i++; } 

i is just a variable. Despite the fact that it was used to iterate over any element that you use, it can still be modified like any other.

0
source

This will do the trick! Remember that you need to define $ i = 0 before the foreach loop if you want to start counting / increasing from 0.

 $i = 0; foreach ($some as $somekey=>$someval) { $i++; } 
0
source
 $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++; } 
0
source

lazy way:

 { $i=1; foreach( $rows as $row){ $i+=1; } } 

but you must have foreach for $ i in order not to exist after foreach or finally turn it off

 $i=1; foreach( $rows as $row){ $i+=1; } unset($i); 

but you must use a loop for this, as leopold wrote.

0
source

All Articles