tags:

views:

191

answers:

3

Hi, I'm having to develop a site on PHP 5.1.6 and I've just come across a bug in my site which isn't happening on 5.2+. When using foreach() to iterate over an object, I get the following error: "Fatal error: Objects used as arrays in post/pre increment/decrement must return values by reference..."

Does anyone know how to convert the following foreach loop to a construct which will work with 5.1.6? Thanks in advance!

foreach ($post['commercial_brands'] as $brand)
                    {
                        $comm_food = new Commercial_food_Model;
                        $comm_food->brand = $brand;
                        $comm_food->feeding_type_id = $f_type->id;
                        $comm_food->save();
                    }
+1  A: 
for ($i = 0; $i < count($post['commercial_brands']); $i++)
{
    $comm_food = new Commercial_food_Model;
    $comm_food->brand = $post['commercial_brands'][$i];
    $comm_food->feeding_type_id = $f_type->id;
    $comm_food->save();
}
Coronatus
Thanks Coronatus, not sure why i thought it would be more complicated than a good old fashioned for loop!
kenny99
A: 

Improving upon Coronatus's answer:

$max = count($post['commercial_brands']);
for ($i = 0; $i < $max; $i++)
{
    $comm_food = new Commercial_food_Model;
    $comm_food->brand = $post['commercial_brands'][$i];
    $comm_food->feeding_type_id = $f_type->id;
    $comm_food->save();
}

You should never have a function in the condition of a loop, because each time the loop goes around it will run the function.

Joshua
Wrong. PHP isn't stupid. It only counts $post once.
Coronatus
Actually, I'm right. It's well known that you need to determine the maximum number of times a for() should loop _before_ the loop.
Joshua
It's why it's possible to change the number of entries in an array _inside_ a for loop and still have it iterate through every one.
Joshua
+1  A: 
$x = 0;
$length = count($post['commercial_brands']);
while($x < $length){
     $comm_food = new Commercial_food_Model;
     $comm_food->brand = $post['commercial_brands'][$x];
     $comm_food->feeding_type_id = $f_type->id;
     $comm_food->save();
     $x++;
}

//while 4 eva

Satanicpuppy