6

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?

4
  • 4
    One of the most important skills a developer can have is the ability to Google.
    – user672118
    Commented Apr 11, 2012 at 23:44
  • What do you mean exists? Does it just have to be defined? Does it have to have a value? Not empty?
    – animuson
    Commented Apr 11, 2012 at 23:55
  • Basically the value of property. For example if [name] contains 'test' perform a particular operation.
    – Rob Fyffe
    Commented Apr 12, 2012 at 0:00
  • You only need to know whether any object has the name 'test', or you need to find the one and only object that has the name 'test', or you need to find all objects with the name 'test'? You could build a dictionary of all the names, or a map from names to objects, or to lists of objects, if they're not unique. Commented Apr 12, 2012 at 16:40

1 Answer 1

6

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
4
  • Thanks. But it's the actual value I need. I have tried various things such as counting the array items and then using a for loop to check weather each name property of each object equals my value. This I think is working at the moment but if there are a lot of objects, could this get quite slow?
    – Rob Fyffe
    Commented Apr 12, 2012 at 9:37
  • @Robert: That would depend on how many objects you have, but there's really no faster way to search through an unsorted list.
    – Ry-
    Commented Apr 12, 2012 at 13:40
  • Is it possible to check multiple properties at a time, instead of using isset() for every property ? Commented Oct 3, 2013 at 14:44
  • @dskanth: You can pass multiple variables to isset, and it’s the same of anding them all together.
    – Ry-
    Commented Oct 3, 2013 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.