Skip to content
Advertisement

PHP check if array contains any key other than some whitelisted

I would like to check all keys of a global GET array and do something, if it contains keys, other than some whitelisted ones from an array.

Let’s say the current url is:

.../index.php?randomekey1=valueX&randomkey2=valueY&acceptedkey1=valueZ&randomkey3=valueA&acceptedkey2=valueB

Just for better visualization: These GET parameters are all available in the global GET variable which looks something like this:

$GET = array(
    "randomekey1" => "valueX",
    "randomkey2" => "valueY",
    "acceptedkey1" => "valueZ",
    "randomkey3" => "valueA",
    "acceptedkey2" => "valueB"
);

The keys I accept and want to let pass, I put into an array too:

$whitelist = array(
    "acceptedkey1",
    "acceptedkey2",
    "acceptedkey3",
);

Now I want to check whether $GET contains any key other than the whitelisted. So in the URL example from above it should return “true”, because there are keys in the $GET array which aren’t in the whitelist.

Not only the existence of such an unknown (none whitelisted) key should trigger a true, but please also its emptyness!


Another example would be the following url:

.../index.php?acceptedkey1=valueZ&acceptedkey3=valueB

This should return false, because no other key other than the ones in the whitelist were found.

Unfortunately I was not able to find any modification of the in_array function or array_search which would fit these requirements, because as far as I know these functions are only looking for something specific, whereas in my requirements I am also looking for something specific (the whitelist keys), but at the same tme I have to check if some unknown keys exist.

Thank you.

Advertisement

Answer

It seems you want to determine whether an array contains keys that don’t exist in a whitelist.
One way to find the difference between arrays is to use array_diff():

array_diff ( array $array1 , array $array2 [, array $… ] ) : array
Returns an array containing all the entries from array1 that are not present in any of the other arrays.

So, it can be used to return all keys from the URL that are not present in the whitelist:

$extrasExist = !empty( array_diff( array_keys($GET), $whitelist ) );
var_dump($extrasExist);

Here’s a demonstration:

$get1 = array(
    "randomekey1" => "valueX",
    "randomkey2" => "valueY",
    "acceptedkey1" => "valueZ",
    "randomkey3" => "valueA",
    "acceptedkey2" => "valueB"
);

$get2 = array(
    "acceptedkey1" => "valueZ",
    "acceptedkey2" => "valueB"
);

$whitelist = array(
    "acceptedkey1",
    "acceptedkey2",
    "acceptedkey3"
);

$extrasExist = !empty(array_diff(array_keys($get1),$whitelist));
var_dump($extrasExist);

$extrasExist = !empty(array_diff(array_keys($get2),$whitelist));
var_dump($extrasExist);

bool(true)
bool(false)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement