开发者

Compare values from 2 arrays

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"); //开发者_JAVA技巧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?


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


You can use array_intersect() to get the values that are both set in that arrays and then check if value is set in the result.

http://php.net/manual/en/function.array-intersect.php

You may also use array_diff() and set if the value is not set in the result.

http://www.php.net/manual/en/function.array-diff.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜