Reputation: 865
I have an array which is given below:
array(1) {
[0]=> array(1) {
["type"]=> string(4) "item"
}
}
I'm using to the following code in an if statement to see if "item" exists in the array but it isn't been evaluated as true
if (array_key_exists('item', $_SESSION['type']))
{
//do something
}
What am I doing wrong?
Upvotes: 0
Views: 3573
Reputation: 7597
Its array in array. And function array_key_exists
checks only one level deep, if the key exists. And your ked is 2 levels deep, so it cant return true, because there is key only "0".
And "item" is not key, but value; you have to use function in_array
or array_search
.
And also you should create your own function for that, because its array in array...
Upvotes: 2
Reputation: 687
You need to use in_array
to find if an element exists in an array.
array_key_exists
checks if the key of the array is present or not
Upvotes: 1
Reputation: 437366
array_key_exists
checks the keys of the array, not the values; "item"
is a value.
To check for the existence of values use either in_array
(if you don't care about the key in case the item is found) or array_search
(if you want to know what the key for that item was). For example:
if (in_array("item", $_SESSION['type'])) // do something
Upvotes: 3