phparraysintersectionwhitelist

Determine if all values in one flat array are found in another flat array


I'm not sure which php function to use for this..

How can I check if one array has the values available in another array?

Fro example, I have a text input where CSV are submitted --- $str = "green, yellow, blue"

I use str_getcsv()to create an array of the string. Then I want to compare array 1 to array 2 seen below

$array2 = array("green", "yellow", "orange", "purple");

I'm comparing array 1 to array 2 to ensure that the submitted values are allowed. So if a value in array 1 does not exist in array 2, I want to return false. I tried the following but it doesn't work.

$array1 = str_getcsv($str); //create array of colors
$array2 = array("green", "yellow", "orange", "purple"); //allowed colors

if (!in_array($array1, $array2)) if value from array1 not in array2
{
    return FALSE;
} else {
    return TRUE;
}

Is this more complicated than I thought?


Solution

  • Look into PHP's array_diff( ) function here: http://php.net/manual/en/function.array-diff.php