Saturnix
Saturnix

Reputation: 10554

Iterating array of objects in PHP

for($i = 0; $i < count($prices); $i++){
error_log($prices[$i]->anObjectVariable);
}

or

foreach ($prices as $price){
error_log($price->anObjectVariable);
}

None of these seems to work, here are the errors I get:

PHP Notice:  Undefined property: price::$anObjectVariable

this is the code which I use to prepare the object(s) and the array.

class price {

    public $anObjectVariable;

}

$prices = array();
    $p = new price();
    $p->anObjectVariable = "PRINT ME IN ERROR LOG!";
    array_push($prices, $p);

Upvotes: 1

Views: 80

Answers (2)

Steve
Steve

Reputation: 8640

I just tested it locally and the following code works fine if you define $prices as an array before you use it.

class price {

    public $anObjectVariable;

}

$prices = array();
$p = new price();
$p->anObjectVariable = "PRINT ME IN ERROR LOG!";
array_push($prices, $p);

for($i = 0; $i < count($prices); $i++){
    echo($prices[$i]->anObjectVariable);
}

Are you actually testing the code you show us above (i.e. the one I just posted above) or are you working on a derivative? Can you confirm that this exact snippet above works for you correctly?

Upvotes: 4

romainberger
romainberger

Reputation: 4558

Then if it's not a typo

for ($i = 0; $i < count($prices); $i++) {
    error_log($prices[$i]->anObjectVariable);
}

should work

Upvotes: 2

Related Questions