kenny99
kenny99

Reputation: 257

How to iterate over an array of objects without foreach and ArrayAccess

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

Upvotes: 1

Views: 4722

Answers (3)

Satanicpuppy
Satanicpuppy

Reputation: 1587

$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

Upvotes: 1

Joshua
Joshua

Reputation: 19

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.

Upvotes: 1

Amy B
Amy B

Reputation: 17977

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

Upvotes: 0

Related Questions