0

I have a need to check if the elements in an array are objects or something else. So far I did it like this:

if((is_object($myArray[0]))) { ... }

However, on occasion situations dictate that the input array does not have indexes that start with zero (or aren't even numeric), therefore asking for $myArray[0] will generate a Notice, but will also return the wrong result in my condition if the first array element actually is an object (but under another index).

The only way I can think of doing here is a foreach loop where I would break out of it right on the first go.

foreach($myArray as $element) {
   $areObjects = (is_object($element));
   break;
}
if(($areObjects)) { ... } 

But I am wondering if there is a faster code than this, because a foreach loop seems unnecessary here.

1
  • 2
    Check here Commented Jan 16, 2015 at 9:10

3 Answers 3

2

you can use reset() function to get first index data from array

if(is_object(reset($myArray))){
 //do here
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could get an array of keys and get the first one:

$keys = array_keys($myArray);
if((is_object($myArray[$keys[0]]))) { ... }

Comments

0

try this

reset($myArray);
$firstElement = current($myArray);

current gets the element in the current index, therefore you should reset the pointer of the array to the first element using reset

http://php.net/manual/en/function.current.php

http://php.net/manual/en/function.reset.php

1 Comment

Warning: current() expects parameter 1 to be array, string given

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.