views:

122

answers:

5

i want to check if one array is contained in the 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

A: 

If you want the smaller array to have only values contained in the bigger, you can do your loop with the smaller array (and thus to have less iterations).

Guillaume Lebourgeois
the array is in same size
Haim Evgi
A: 
function checkSameValues($a, $b){
   if ( in_array($a,$b) ) return true;
   else return false;
}
Marcx
i need to check the same key and the same value , in_array check only values!
Haim Evgi
+1  A: 

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.

Cristian
not work the same for me , i get different results
Haim Evgi
I modified and tested it... it works for me.
Cristian
+3  A: 

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";
M42
A: 

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
Dennis Haarbrink