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?
Surprisingly
array_keys_exist
doesn't exist?! In the interim that leaves some space to figure out a single line expression for this common task. I'm thinking of a shell script or another small program.Note: each of the following solutions use concise
[…]
array declaration syntax available in php 5.4+array_diff + array_keys
(hat tip to Kim Stacks)
This approach is the most brief I've found.
array_diff()
returns an array of items present in argument 1 not present in argument2. Therefore an empty array indicates all keys were found. In php 5.5 you could simplify0 === count(…)
to be simplyempty(…)
.array_reduce + unset
Harder to read, easy to change.
array_reduce()
uses a callback to iterate over an array to arrive at a value. By feeding the keys we're interested in the$initial
value of$in
and then removing keys found in source we can expect to end with 0 elements if all keys were found.The construction is easy to modify since the keys we're interested in fit nicely on the bottom line.
array_filter & in_array
Simpler to write than the
array_reduce
solution but slightly tricker to edit.array_filter
is also an iterative callback that allows you to create a filtered array by returning true (copy item to new array) or false (don't copy) in the callback. The gotchya is that you must change2
to the number of items you expect.This can be made more durable but verge's on preposterous readability:
If you have something like this:
You could simply
count()
:This only works if you know for sure that you ONLY have these array keys, and nothing else.
Using array_key_exists() only supports checking one key at a time, so you will need to check both seperately:
array_key_exists()
returns true if the key is present in the array, but it is a real function and a lot to type. The language constructisset()
will almost do the same, except if the tested value is NULL:Additionally isset allows to check multiple variables at once:
Now, to optimize the test for stuff that is set, you'd better use this "if":
It seems to me, that the easiest method by far would be this:
Prints:
This also allows to check which keys are missing exactly. This might be useful for error handling.
Will return true, because there are keys from $keys array in $myArray
Hope this helps:
This is the function I wrote for myself to use within a class.
I am assuming you need to check for multiple keys ALL EXIST in an array. If you are looking for a match of at least one key, let me know so I can provide another function.
Codepad here http://codepad.viper-7.com/AKVPCH