1

I have an array with stdClass objects as below. How would I count how many I have under Interviewee_Name?

Tried counting as I would do an array but get an error that I can't becaused of the stdClass Object and then unsure how to proceed from there

Array
(
    [0] => stdClass Object
        (
            [Interviewee_Name] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => rn_Interviewee_Name_DIR_27
                            [value] => Janusz Jasinski
                        )

                )

        )
1
  • Can you show what you tried to do? You should be able to count any array, regardless of what it contains. Commented Oct 25, 2017 at 15:30

2 Answers 2

2

This'll get the number of elements under Interviewee_Name, but it'll count all elements, not just objects.

count($arr[0]->Interviewee_Name)

However, if you really only want to get the objects in Interviewee_Name, you'll need to array_filter the array to get only the objects, and then count that new array:

count(array_filter($arr[0]->Interviewee_Name, function ($el) {
    return (gettype($el) == 'object');
}));

The syntax for getting an element from an array looks like $arr['index'], but in this case Interviewee_Name is a property of an object so you need to use the object syntax: $obj->prop

Sign up to request clarification or add additional context in comments.

3 Comments

So if I wanted to get the value, would I do $arr[0]->Interviewee_Name[0]->value?
@pee2pee What doesn't work, the second block of code to filter non-objects, or your code to get the value?
Ignore me - using $arr but I changed it to $a :-)
1
$array = json_decode(json_encode($formData), True);

I added that to before looking to do a count and it worked!

1 Comment

Yes, the second parameter indicates that json_decode will convert $formData into an associative array instead of an object, however, this is unnecessary overhead that could be avoided if you simply change how you get Interviewee_Name

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.