I have a model that checks for entries en a database. Like this:
public function getByID($id) { if(false == is_numeric($id)) return false; $images = array(); $query = $this->db->where("id_album", $id)->order_by("order", "ASC")->get("images"); foreach($query->result() as $row) $images[] = $row; return (object) $images; }
In my view I want to know if I have a rows or not, to show the images or not. I do this:
<?php if(false != isset($content->images)): ?> <pre><?php print_r($content->images); ?></pre> <?php endif; ?>
But every time I try to skip when I've no results (i get a stdClass() empty) I fail. I tried isset
, $content->images != NULL
, !$content->images
... I don't know how to do it to skip the "Severity: Notice Message: Undefined variable".
Thank you in advance.
UPDATE:
$content
has more sets than images, like $content->_data
or $content->title
.
When I've NO images on database and i've no return from MySQL, doing this:
<?php echo count($content->images); ?> <pre><?php print_r($content->images); ?></pre>
The output is:
1 stdClass ( )
2 answers. You could use the get_object_vars function to return the properties of stdClass to array . Then you could use the function count or empty , to know if it is empty or not.
The count() function is used to count the elements of an array or the properties of an object. Note: For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.
The stdClass is the empty class in PHP which is used to cast other types to object. It is similar to Java or Python object. The stdClass is not the base class of the objects. If an object is converted to object, it is not modified.
why cant you just use
if(isset($content->images)) //Isset also will make sure $content is set { }
This way your performing checks on both entities.
As images is an object that can be iterated you can also check that.
if(isset($content->images) && is_object($content->images)) { }
Also you seem to be using the wrong comparison operators for boolean's, you should be using the strict standards for comparison, which is ===
and not ==
, or !==
and not !=
:)
Merry Christmas
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With