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

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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));
How to&Answers:

why don’t you use array_key_exists ?

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

Answer:

Try this,

$array->offsetExists('1QmRjtsw2UQ');