44

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 ( )
ipalaus
  • 2,253
  • 4
  • 27
  • 42

6 Answers6

88

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 !=:)

VLAZ
  • 26,331
  • 9
  • 49
  • 67
RobertPitt
  • 56,863
  • 21
  • 114
  • 161
  • Hey! Merry Christmas! I've updated the question. I don't understand why when doing a count($content->images); without any entry returns me 1... Thank you in advance! – ipalaus Dec 24 '10 at 19:31
  • try and `print_r($content)` to see what it shows, maybe the issue is its actually `$content->images[0]` which then holds the array! – RobertPitt Dec 24 '10 at 19:33
  • what about php reflection ??? http://php.net/manual/en/book.reflection.php , it can do that too – tawfekov Dec 24 '10 at 19:42
  • Reflections should be used on a larger scale in My Opinion, do you not think that's a little bulky when you have functions like `isset`,`empty`,`count`,`is_(array|object|scaler)` ? – RobertPitt Dec 24 '10 at 19:46
19

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: http://us1.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>';
    }
?>
Anthony
  • 2,014
  • 2
  • 19
  • 29
lucifurious
  • 630
  • 5
  • 11
9

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
Damien Overeem
  • 4,487
  • 4
  • 36
  • 55
  • This solved my problem too. I needed to check if an object has a property set, even if it is null. I used array_key_exists as completion of your solution. +1. Thanks – Liglo App Nov 18 '13 at 09:38
  • In your case I suggest not using `array_key_exists`, but `isset($array[$index])`. The latter is much faster, see: http://stackoverflow.com/questions/6337893/why-is-array-key-exists-1000x-slower-than-isset-on-referenced-arrays for more details. – Damien Overeem Nov 18 '13 at 12:32
  • @DamienOvereem using `isset` will detect the existence of a property set to null. – chiliNUT Mar 21 '14 at 16:57
2

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

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
1

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";
ironchicken
  • 754
  • 6
  • 19
0

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
}
MCollard
  • 926
  • 2
  • 20
  • 39