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.

Digital Ninja
  • 3,415
  • 5
  • 26
  • 51

3 Answers3

2

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

if(is_object(reset($myArray))){
 //do here
}
Girish
  • 11,907
  • 3
  • 34
  • 51
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

Att3t
  • 466
  • 2
  • 8
0

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

$keys = array_keys($myArray);
if((is_object($myArray[$keys[0]]))) { ... }
Serpes
  • 672
  • 4
  • 14