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?
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;
}