Question

I need to check if an array of DOMNode objects contains all the items in a similar array of DOMNode objects.

In general, to check if an array contains another array, I've tried some of the methods outlined in this question. However, both array_intersect() and array_diff() compare array items on the bases (string) $elem1 === (string) $elem2 - which throws the following error for DOMElements as they can't be converted to strings.

PHP Catchable fatal error: 
Object of class DOMElement could not be converted to string in...

What would be the proper way of handling this?

Was it helpful?

Solution

I've made this which seems to work, as example i filled both arrays with all kinds of objects and types just to see if it works:

$array = array(new DOMDocument(), 'foobar', 112312, new DateTime('Y'));
$array2 = array(new DOMDocument(), 'foobar',12312, false, new DateTime('Y'), 112312, true);

var_dump(array_diff_two($array,$array2)); //returns true

$array = array(new DOMDocument(), 'foobar', 112312, new DateTime('m'));
$array2 = array(new DOMDocument(), 'lorem ipsum!',12312, false, new DateTime('Y'), 112312, true);

var_dump(array_diff_two($array,$array2)); //returns false

function array_diff_two($array1, $array2){
    // serialize all values from array 2 which we will check if they contain values from array 1
    $serialized2 = array();
    foreach ($array2 as $value){
        $serialized2[] = serialize($value);
    }

    // Check if all values from array 1 are in 2, return false if it's not found
    foreach ($array1 as $value) {
        if (! in_array(serialize($value), $serialized2)) {
            return false;
        }
    }
    return true;
}

OTHER TIPS

As I've written it now, here's an alternative solution. Tim's solution is more readable, in my opinion.

//Does array of DOMNodes contain other array DOMNodes
private function array_contains_array($haystack,$needle){
    //Create object hash array of $haystack
    $haystackHashArr = array();
    foreach ($haystack as $idx => $haystackObj) {
        $haystackHashArr[$idx] = spl_object_hash($haystackObj);
    }

    //Now search for hashes of needle array objects in Haystack-hash-Array
    foreach ($needle as $domNode) {
        $huntedForHash = spl_object_hash($domNode);
        foreach($haystackHashArr as $hsHash){
            if ($hsHash == $huntedForHash) continue 2;
        }
        //Only get here if an item not found (Due to continue statement)
        return false;
    }
    return true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top