JROB JROB - 1 month ago 10x
PHP Question

Checking if all values in one array exist in another array

I am trying to check if all required values exist in an array. I thought using

would be what I should be using:

$required[0] = 'FirstName';
$required[1] = 'LastName';

$posted['Email'] = 'none@example.com';
$posted['FirstName'] = 'Bob';
$posted['Group'] = '5';

print_r(array_intersect($required, $posted));

So, I want to be sure that "FirstName" and "LastName" exist in the
array. However, "LastName" is missing, but this returns an empty array result.

What am I missing?


If $posted originally comes from $_POST at some point, (as in the values from inputs on a form), all of the keys will be set, even though some may be set to ''. Since you have keys as values in your $required array, It's probably best to just check the required fields in a loop. You can use empty to simultaneously verify that they exist and have truthy values. Assuming the following code is the body of a function or the contents of a file, something like this should work:

foreach ($required as $requirement) {
    // if everything has to have a value, just return false as soon as something doesn't
    if (empty($posted[$requirement]) return false;
return true;

Part of why the way you're doing it with array_intersect isn't working because that function will check the values in $required against the values in $posted, and you need to check the values in $required against the keys in $posted. The other part is that array_intersect will return the values that the two arrays have in common, not the ones that are missing.

If some of the keys in $posted really may not exist, it may be better to define your $required array by key instead of by value, and then use array_diff_key.

$required['FirstName'] = true;
$required['LastName'] = true;

$missing_requirements = array_diff_key($required, $posted);

If every key in $required is present in $posted, the result will be an empty array, which will evaluate to false.