0

How do I check that an array key equals a value with an array like this:

Array ( [0] => stdClass Object ( [subCategory] => All Headphones [description] => [image] => ) [1] => stdClass Object ( [subCategory] => Behind-the-Neck Headphones [description] => [image] => ) [2] => stdClass Object ( [subCategory] => Clip-On Headphones [description] => [image] => ) [3] => stdClass Object ( [subCategory] => Earbud Headphones [description] => [image] => ) [4] => stdClass Object ( [subCategory] => Kids' Headphones [description] => [image] => ) )

I've tried using this code:

if(array_key_exists('subCategory',$array) {
          echo "Exists";
}
1
  • 1
    what you are trying to access are not array keys but rather object properties. so tell us first what you actually want to achieve ? Commented Jan 5, 2012 at 4:17

2 Answers 2

4

That wont work because you have an array of standard objects... the only array keys even present are integers. So the question is what are you trying to detect? If you want to check the if an object has the subCategory property you can do isset($obj->subCategory). If you want to ensure that each object in your array has that property then you need to loop:

function hasSubCategory($array){
  foreach($array as $element) {
    if(!isset($element->subCategory)){
      return false; // if any object doesnt have the property
    }
  }

  return true; // if all objects have the property
}

I dont think thats what you really want to do though, some more info would be helpful.

Sign up to request clarification or add additional context in comments.

Comments

0

Seems like you are using fetch_object(). This gives you array of objects. If you want to work with arrays use fetch_assoc() To use array_key_exists you need to loop the result because it is multidimensional array.

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.