1

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
  • $post['commercial_brands'] is an object ? Commented Jun 2, 2010 at 14:51

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
1
$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

Comments

0
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();
}

1 Comment

Thanks Coronatus, not sure why i thought it would be more complicated than a good old fashioned for loop!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.