2

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

4 Answers 4

3

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";
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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

1 Comment

i need to check the same key and the same value , in_array check only values!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.