I’m trying to check that user’s submitted data, from $_POST, has at least the same elements that my passed array has. I’m doing it because I will use those elements later by calling $_POST['element'] and I don’t like errors about that element doesn’t exist (isn’t set). 🙂
I don’t want to use something like isset($_POST['x'], $_POST['y'], $_POST['z']) because each time I need to rewrite $_POST and it seems unreadable as well.
I tried to use in_array(array('x', 'y', 'z'), $_POST), but it doesn’t work (it returns false when it should return true). Any ideas how to make that work? 🙂 I’m sure that I have empty strings as $_POST['x'], $_POST['y'] and $_POST['z']. I even tried to change values of hose three $_POST elements to something other than empty string – still… doesn’y work as expected. 🙁
Thanks in an advice! 🙂
Edit:
Just found out that in_array() checks values, not keys. Then, I tried to do like this…
in_array(array('title', 'slug', 'content'), array_keys($_POST))
Still, it returns false. How does it comes so? ;/
Edit #2:
Okay, here are results of debugging…
Incoming $_POST:
array(3) {
["title"]=>
string(0) ""
["slug"]=>
string(0) ""
["content"]=>
string(0) ""
}
Result of array_keys($_POST):
array(3) {
[0]=>
string(5) "title"
[1]=>
string(4) "slug"
[2]=>
string(7) "content"
}
Result of in_array(array('title', 'slug', 'content'), array_keys($_POST)):
bool(false)
The question… why is it false? I did all correct, as much as I know.
Edit #3:
At the end, I created my own method called Arr::keys_exists($keys, $array).
in_array()checks to see if a value exists in an array, not a key. If you want to check to see if a key exists, then you’d want something like…or the simpler…
If you want to check for many keys at once: