1

Here is an array object that contains an array [body]. How do I get to know that this object has array inside and give me it's keys?

Array
(
    [6] => stdClass Object
        (
            [vid] => 6
            [uid] => 1
            [title] => om
            [log] => 
            [status] => 1
            [comment] => 2
            [promote] => 0
            [sticky] => 0
            [nid] => 6
            [type] => article
            [language] => und
            [created] => 1436514497
            [changed] => 1438003101
            [tnid] => 0
            [translate] => 0
            [revision_timestamp] => 1438003101
            [revision_uid] => 1
            [body] => Array
                (
                    [und] => Array
                        (
                            [0] => Array
                                (
                                    [value]

3 Answers 3

2

You need to check whether the object has body property, which is array and which should not be empty.

And fetch the keys it all three conditions fulfill.

Use is_array(), array_keys() and isset()

if (isset($obj->body) && is_array($obj->body) && ! empty($obj->body)) {
  // yes it has
  $keys = array_keys($obj->body);
}
else {
  // either body is not there or body is empty. 
}

EDIT:

Check if any of the object properties is an array and return its keys.

foreach (get_object_vars($obj) as $var) {
  if (gettype($var) == 'array') {
    $keys = array_keys($var);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I don't want to check whether the object has body property, instead, I want to check if there is ANY array EXISTS in this object, and if yes, give me its key.
when I am doing print_r($keys);die; outside if condition, it is giving me nothing. It seems like, it always check first value in array i.e. vid and it is string not an array, IT IS CHECKING ALL VALUES. I also did print_r at the end of foreach loop, this also gives me blank result.
1

Considering $main_array as your given result. Try this

if( is_array($main_array->body) )
{
// do your process
}

1 Comment

I want something like this way.Suppose $compfield is my main array.So foreach ($compfields as $comp => $comps){foreach ($comps as $value=>$values) {if(is_array($value)){print ($value); } }} and in $value, I want body
0

Check if it is an array with:

http://php.net/manual/de/function.is-array.php

1 Comment

If you are going to ask the OP to RTM, just post your hint as a comment under the question. There is not enough effort to educate in this answer.

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.