ipalaus
ipalaus

Reputation: 2273

Check if a stdClass object has "entries" in 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 ( )

Upvotes: 45

Views: 72886

Answers (6)

RobertPitt
RobertPitt

Reputation: 57268

Why can't 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 !=:)

Upvotes: 89

lucifurious
lucifurious

Reputation: 640

I know this is an old question but it still hasn't been answered properly.

isset only tests if a key exists and not if it is null. This is an important distinction. See the examples: https://www.php.net/isset

To properly test if an array contains a key, array_key_exists should be used as stated elsewhere on this page.

On the other hand, to test if an object contains a property, the property_exists method should be used. property_exists() returns TRUE even if the property has a NULL value.

So, your code should look like this (yeah, I changed it a bit but the point remains the same):

<?php
    if ( isset( $content ) && property_exists( $content, 'images' ) ) {
        echo '<pre>' . print_r( $content->images, true ) . '</pre>';
    }
?>

Upvotes: 20

ironchicken
ironchicken

Reputation: 794

I wanted to check if some object has all of the given properties. So I did this:

function hasAllProperties($object, array $properties) {
    return array_reduce(
        $properties,
        function ($acc, $property) use ($object) {
            return $acc && property_exists($object, $property);
        },
        true
    );
};

$someObject = json_decode('{"foo": "bar", "baz": "quux"}');

echo 'should be true ' . (hasAllProperties($someObject, ['foo', 'baz']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAllProperties($someObject, ['foo', 'baz', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAllProperties($someObject, ['foo', 'moo']) ? 'TRUE' : 'FALSE') . "\n";

Then in addition you may also want to check if just one or more of the properties exists:

function hasAnyProperties($object, array $properties) {
    return array_reduce(
        $properties,
        function ($acc, $property) use ($object) {
            return $acc || property_exists($object, $property);
        },
        false
    );
};

$someObject = json_decode('{"foo": "bar", "baz": "quux"}');

echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'baz']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'baz', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be true ' . (hasAnyProperties($someObject, ['foo', 'moo']) ? 'TRUE' : 'FALSE') . "\n";
echo 'should be false ' . (hasAnyProperties($someObject, ['moo']) ? 'TRUE' : 'FALSE') . "\n";

Upvotes: 1

CyrilRegal
CyrilRegal

Reputation: 1

If i want to test the whole object to know if i do something or not i proced like that:

if($object != new stdClass())
{
    // do something
}

Upvotes: 0

Damien Overeem
Damien Overeem

Reputation: 4529

Ran into this question/answers while trying to find out how to check for an empty stdClass.

The given answers are not really answers to the question in the topic, leading people here that wont get a clear answer, so I'll add an improved version:

Question: Check if a stdClass object has “entries” in PHP

Answer:

Typecast the stdClass to array, see below:

$someObject = new StdClass();
var_dump(empty($someObject)); // Will return false, because $someObject is an stdClass

// Convert to array
$someObjectArr = (array)$someObject;
var_dump(empty($someObjectArray)); // Will return true

Upvotes: 9

Jacob Relkin
Jacob Relkin

Reputation: 163288

Use count with isset:

if(isset($content) && count($content)) {
  //$content has properties...
  if(isset($content->images)) { //$content->images exists
    //awesome stuff goes here...
  }  
}

codepad example

Upvotes: 2

Related Questions