Haim Evgi
Haim Evgi

Reputation: 125466

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

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

Upvotes: 2

Views: 686

Answers (4)

Dennis Haarbrink
Dennis Haarbrink

Reputation: 3760

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

Upvotes: 0

Toto
Toto

Reputation: 91385

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";

Upvotes: 3

Cristian
Cristian

Reputation: 200080

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.

Upvotes: 1

Marcx
Marcx

Reputation: 6826

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

Upvotes: 0

Related Questions