Digital Ninja
Digital Ninja

Reputation: 3731

Checking the first element of array, regardless of array indexes

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.

Upvotes: 0

Views: 343

Answers (3)

Att3t
Att3t

Reputation: 466

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

Upvotes: 0

Serpes
Serpes

Reputation: 672

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

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

Upvotes: 0

Girish
Girish

Reputation: 12117

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

if(is_object(reset($myArray))){
 //do here
}

Upvotes: 2

Related Questions