for loop with assignment in php

When I want to iterate an array I usually do:

foreach ($array as $a)
   //do something with $a

I just want to know if is possible do something like this with a for loop:

for ($i = 0; $i < count($array); $a = $array[$i]; $i ++)
   //do something with $a

Edit: When I test the code above, the for syntax is not valid.


skip the $a = $array[$i] part of the for-loop (This is assigned INSIDE of the loop and not in the declaration of the loop)

You should do like this instead:

for ($i = 0; $i < count($array); $i ++)
   $a = $array[$i]; //Gets value of element in array $array
   //Do something with it...

You say you want control of the element of an array. You can do the equalivalent by doing like this (adding a key-value to the foreach-loop)

foreach ($array as $key=>$i)
   $a = $i[$key];

Replace the third semicolon with a comma. It's not the entire solution (assignment is done too late), but it should explain sufficiently how a for statement works.

The for loop doesn't need to handle the $a = $array[$i]; as part of its arguments. You can just move it to the body of the loop, something like this: for ($i = 0; $i < count($array); $i++){ $a = $array[$i]; //do something with $a }

Need Your Help

Rails Newbie: Appending conditions in activerecord?

ruby-on-rails activerecord

I have a form which is used to filter queries. Some of the form attributes are optional; I'm just wondering how to append them as activerecord conditions if (and only if) they have a set value?

C# StackOverFlowException when creating new instance of class

c# wpf stack-overflow instance

Hm i get a strange problem. when i creating new instance of class i get StackOverflowExcepion :)

Referencing a composite primary key

sql oracle foreign-keys primary-key composite-primary-key

I have two tables, with each table having a composite primary key.