Search code examples
phparraysvalidationwhitelist

Validate that user submission has at least one whitelisted value and no blacklisted values


I know there are a lot of these, but I'm looking for something slightly different.

A straight diff won't work for me.

I have a list (array) of allowed tags i.e.

["engine", "chassis", "brakes", "suspension"]

Which I want to check with the list the user has entered. Diff won't work, because the user may not enter all the options i.e. ["engine"] but I still want this to pass. What I want to happen is fail if they put something like banana in the list.


Solution

  • Use array_diff();

    $allowed=array("engine","chassis","brakes","suspension");
    $user=array("engine","brakes","banana");
    $unallowed=array_diff($user, $allowed);
    print_r($unallowed);
    

    This will return banana, as it is in $user, but not in $allowed.