How can I check if an array contains a specific key in php

857 Views Asked by At

I know how to check for a value in an array, but how do I check for a value in an Array Iterator?

$array = new ArrayIterator(array(
'1QmRjtsw2UQ' => array('pubdate' => '26 Jun 15', 'alt' => '8 Year Old Beautifully Covers Thinking Out Loud', 'anchor text' => '8-yo \'Thinking Out Loud\''),
'eKqLaYrcf3A' => array('pubdate' => '25 Jun 15', 'alt' => 'Plane Lands On Truck', 'anchor text' => 'Plane Lands On Truck'),
));

I'm trying to check for the values such as 1QmRjtsw2UQ.

This does not work:

if(in_array('1QmRjtsw2UQ', $array));
2

There are 2 best solutions below

0
GAMITG On

Try this,

$array->offsetExists('1QmRjtsw2UQ');
3
Akshay Hegde On

why don't you use array_key_exists ?

if(array_key_exists('1QmRjtsw2UQ', $array)) 
{
      // do something
}

--- 2024-03-08---

Above solution works only if 2nd argument is an array as of PHP >=8

If second argument is an object then above solution is deprecated as of PHP 7.4.0, and removed as of PHP 8.0.0.

To check whether a property exists in an object, use property_exists() function refer: https://www.php.net/manual/en/function.property-exists.php