Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment a value inside php foreach?

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++)
{

}
like image 420
gvm Avatar asked Jun 15 '12 09:06

gvm


People also ask

How to increment count in PHP?

C style increment and decrement operators represented by ++ and -- respectively are defined in PHP also. As the name suggests, ++ the increment operator increments value of operand variable by 1. The Decrement operator -- decrements the value by 1.

Is foreach faster than for PHP?

In short: foreach is faster than foreach with reference.

Does PHP have foreach?

The PHP foreach LoopThe foreach loop works only on arrays, and is used to loop through each key/value pair in an array.


1 Answers

No, you will have to use

$i = 0;
foreach ($some as $somekey=>$someval) {
    //xyz
    $i++;
}
like image 144
Ananth Avatar answered Oct 07 '22 08:10

Ananth