I have a variety of arrays that will either contain
story & message
or just
story
How would I check to see if an array contains both story and message? array_key_exists()
only looks for that single key in the array.
Is there a way to do this?
The above solutions are clever, but very slow. A simple foreach loop with isset is more than twice as fast as the
array_intersect_key
solution.(344ms vs 768ms for 1000000 iterations)
One more solution in the collection:
If you only have 2 keys to check (like in the original question), it's probably easy enough to just call
array_key_exists()
twice to check if the keys exists.However this obviously doesn't scale up well to many keys. In that situation a custom function would help.
Here is a solution that's scalable, even if you want to check for a large number of keys:
What about this:
only return true if both are not null
if is null, key is not in array
try this