Array_key_exists()

I have this

echo '<pre>';print_r($removed_assets);echo '</pre>';
if (array_key_exists("blade_server_id",$removed_assets))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }

but why is the key not found

Array
(
    [0] => Array
        (
            [blade_server_id] => 1
            [name] => 
            [manufacturer] => Brocade
            [model] => VDX 2730
            [updated_date] => 2021-09-11 11:43:40
            [updated_by] => lurtnowski@industechnology.com
        )

)

Key does not exist! 

This:-

Note :
array_key_exists() will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found.

https://www.php.net/manual/en/function.array-key-exists.php

Try:-

if (array_key_exists("blade_server_id",$removed_assets[0]))
3 Likes

I think the problem with relying on index keys is that you have to know the specific index key to work with your array. It’s easy when you know there’s only 1 data set being returned, but what if there are multiple data sets being returned? Then the index of 0 will only show 1 data set from your results rather than say 5 data sets.

I think for this it might be overkill, but I’d use a foreach loop and then check against blade_server_id.

Just my 2 cent.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.