Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search objects to see if they contain a specific value?

I have various objects that look like this:

Array
(
[0] => stdClass Object
    (
        [tid] => 18
        [vid] => 1
        [name] => test
        [description] => 
        [format] => 
        [weight] => 0
        [depth] => 0
        [parents] => Array
            (
                [0] => 0
            )

    )

[1] => stdClass Object
    (
        [tid] => 21
        [vid] => 1
        [name] => tag
        [description] => 
        [format] => 
        [weight] => 0
        [depth] => 0
        [parents] => Array
            (
                [0] => 0
            )

    )
)

Basically I need to find out weather a [name] value exists in these objects, how do I go about doing this?

like image 608
Rob Fyffe Avatar asked Apr 11 '12 23:04

Rob Fyffe


1 Answers

To check if the name property exists in an object:

if(isset($obj->name)) {
    // It exists!
}

So, if you want to find those objects that had $name properties:

$result = array_filter($myArray, function($x) {
    return isset($x->name);
}); // Assuming PHP 5.3 or higher
like image 91
Ry- Avatar answered Oct 14 '22 01:10

Ry-