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?

3
  • 2
    its down a dimension see the first [0] => Array Commented Jun 29, 2017 at 21:36
  • 2
    Looks like your array has another array in it. Commented Jun 29, 2017 at 21:36
  • 2
    Possible duplicate of array_key_exists is not working Commented Jun 29, 2017 at 21:41

2 Answers 2

3

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

...
if (array_key_exists("image_id", $myarray[0]))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, makes sense now. Could it be modified so that it wouldn't matter how many levels there are?
@fightstarr20, welcome. Yes, it can be modified to check if image_id key exists on any array level, but it sounds like new input condition
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.