I’m getting an error and I’ve googled everything I can think of with barely any insights. Maybe you can help with a fresh set of eyes.
I have a function that returns an array of objects. The code that calls this function then loops through this array and does what it needs to do with each object. It seems to work visually when it spits out the HTML, but the server logs still give an error ‘Invalid argument supplied for foreach()’. Yeah, it’s great that it works technically, but I don’t want this error to pop up anymore. Thoughts?
<?php // The class whose method returns an array of library_Label objects class library_Label { public $id = null; public $name = null; public function getChildren() { // $children is declared earlier return $children; } } // main code $columns = new library_Label(1); foreach ($columns->getChildren() as $label) echo $label->Name; ?>
This is fairly common, my solution is always to change this:
to
It should cover all situations.
You can expand it to a full if statement with braces as well and then include an else block to handle the situation when children is empty if you want to.