Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a stdClass object has "entries" in PHP

Tags:

php

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 ( ) 
like image 391
ipalaus Avatar asked Dec 24 '10 19:12

ipalaus


People also ask

How check stdClass object is empty or not in PHP?

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.

How do you count elements in an object in PHP?

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.

What is stdClass object in PHP?

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.


1 Answers

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

like image 200
RobertPitt Avatar answered Sep 16 '22 14:09

RobertPitt