开发者

compare arrays : one array is contained in the second array (key+value)

i want to check if one array is contained in the开发者_StackOverflow社区 second array , but the same key and the same values,

(not need to be equal, only check that all the key and value in one array is in the second)

the simple thing that i do until now is :

function checkSameValues($a, $b){

        foreach($a as $k1 => $v1){                                  
            if($v1 && $v1 != $b[$k1]){
                return false;
                break;                                      
            }
        }
        return true;
    }

Is there a simpler(faster) way to check this ?

thanks


I would do

$array1 = array("a" => "green", "b" => "blue", "c" => "white", "d" => "red");
$array2 = array("a" => "green", "b" => "blue", "d" => "red");
$result = array_diff_assoc($array2, $array1);
if (!count($result)) echo "array2 is contained in array";


What about...

$intersect = array_intersect_assoc($a, $b);
if( count($intersect) == count($b) ){
    echo "yes, it's inside";
}
else{
    echo "no, it's not.";
}

array_intersect_assoc array_intersect_assoc() returns an array containing all the values of array1 that are present in all the arguments.


function checkSameValues($a, $b){
   if ( in_array($a,$b) ) return true;
   else return false;
}


This obviously only checks depth=1, but could easily be adapted to be recursive:

// check if $a2 is contained in $a1
function checkSameValues($a1, $a2)
{
    foreach($a1 as $element)
    {
        if($element == $a2) return true;
    }
    return false;
}

$a1 = array('foo' => 'bar', 'bar' => 'baz');
$a2 = array('el' => 'one', 'another' => $a1);

var_dump(checkSameValues($a2, $a1)); // true
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜