User gives me a $_POST, I want to check whether keys (not the values) are there.
$_POST keys need to be newemail, firstPassword and secondPassword.

What I have tried:
if (in_array(array_keys($_POST), array("newemail", "firstPassword", "secondPassword"))) echo "Everything in order"..

How to make it actually work?

Dani AI

Generated

Good idea from — treat the required keys as a set rather than trying to test an array inside in_array. A concise, idiomatic way to get which required keys are missing is to flip the required list into keys and compare against $_POST:

$required = ['newemail', 'firstPassword', 'secondPassword'];
$missing = array_diff_key(array_flip($required), $_POST);

if (empty($missing)) {
    // all required keys are present
} else {
    // $missing lists which keys are absent
}

If you prefer an explicit, easy-to-read check (and want to collect which single key is missing as you go), loop with array_key_exists:

$required = ['newemail', 'firstPassword', 'secondPassword'];
$missing = [];

foreach ($required as $k) {
    if (!array_key_exists($k, $_POST)) {
        $missing[] = $k;
    }
}

Notes and pitfalls to watch for: use array_key_exists when you only care that a key exists (it returns true even if the value is null); isset will return false for null. PHP array keys are case-sensitive — if incoming keys might vary in case, normalize both sides (for example by lowercasing) before comparing. To enforce a strict whitelist (no unexpected keys), compare $_POST keys against your required list and handle extras accordingly.

Finally, presence check is only step one: always validate and sanitize the values (email format, password rules), and protect the endpoint (CSRF tokens, rate limiting) before trusting input.

Recommended Answers

All 2 Replies

http://php.net/array_intersect

The result of the intersect of both arrays, should be an array identical to array("newemail", "firstPassword", "secondPassword")

So, if you do an array_diff() on those two next, you should have an empty array.

Hope it makes sense.

It's so hard, yet so easy. Exactly that. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.