0

I have a PHP array that looks like this if I print_r($myarray)

Array ( [0] => Array ( [description] => testdecr [link] => testlink [image_id] => 150 ) )

I am trying to check for a key called image_id by doing this...

if (array_key_exists("image_id",$myarray)) {
        echo 'Image_id exists';
    }

This is not working, anyone any ideas what I am doing wrong?

fightstarr20
  • 11,682
  • 40
  • 154
  • 278

2 Answers2

3

"image_id" key is on nested array under position 0.
It should be:

...
if (array_key_exists("image_id", $myarray[0]))
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

You can use this function if you use a multi-dimensional array.

function array_key_exists_in_multi($key, $array)
        {
            $result = array_key_exists($key, $array);
            foreach ($array as $value) {
                $result = (is_array($value)) ? array_key_exists_in_multi($key, $value) : $result;
                if ($result) return $result;
            }
            return $result;
        }

This simple few lines function returns true if it finds any key from the array.

Example of the function:

if we pass this array as a parameter in the function, we can get the expected result.

$arr = array(
            '1' => 100,
            '2' => array(
                '16' => 200,
                '18' => array(
                    'example' => 100,
                    '101' => 101
                ),
            ),
            '3' => 400
        );

print array_key_exists_in_multi('example', $arr); //Output is: 1
print array_key_exists_in_multi('16', $arr); //Output is: 1
print array_key_exists_in_multi('2', $arr); //Output is: 1
print array_key_exists_in_multi('20', $arr); //Output is: 0