note 111675 added to function.array-diff-assoc
| From: | Giosh | Date: | Fri, 15 Mar 2013 11:15:23 +0000 |
| Subject: | note 111675 added to function.array-diff-assoc | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-194081@lists.php.net to get a copy of this message | ||
The array_diff_assoc_array from "chinello at gmail dot com" (and others) will not work for
arrays with null values. That's because !isset is true when an array key doesn't exists or
is set to null.
(sorry for the changed indent-style)
<?php
function array_diff_assoc_recursive($array1, $array2) {
$difference=array();
foreach($array1 as $key => $value) {
if( is_array($value) ) {
if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
$difference[$key] = $value;
} else {
$new_diff = array_diff_assoc_recursive($value, $array2[$key]);
if( !empty($new_diff) )
$difference[$key] = $new_diff;
}
} else if( !array_key_exists($key,$array2) || $array2[$key] !== $value ) {
$difference[$key] = $value;
}
}
return $difference;
}
?>
And here an example (note index 'b' in the output):
<?php
$a1=array( 'a' => 0, 'b' => null, 'c' => array( 'd'
=> null ) );
$a2=array( 'a' => 0, 'b' => null );
var_dump( array_diff_assoc_recursive( $a1, $a2 ) );
var_dump( chinello_array_diff_assoc_recursive( $a1, $a2 ) );
?>
array(1) {
["c"]=>
array(1) {
["d"]=>
NULL
}
}
array(2) {
["b"]=>
NULL
["c"]=>
array(1) {
["d"]=>
NULL
}
}
----
Server IP: 69.147.83.199
Probable Submitter: 79.14.2.62
----
Manual Page -- http://php.net/manual/en/function.array-diff-assoc.php
Edit -- https://master.php.net/note/edit/111675
Del: integrated -- https://master.php.net/note/delete/111675/integrated
Del: useless -- https://master.php.net/note/delete/111675/useless
Del: bad code -- https://master.php.net/note/delete/111675/bad+code
Del: spam -- https://master.php.net/note/delete/111675/spam
Del: non-english -- https://master.php.net/note/delete/111675/non-english
Del: in docs -- https://master.php.net/note/delete/111675/in+docs
Del: other reasons-- https://master.php.net/note/delete/111675
Reject -- https://master.php.net/note/reject/111675
Search -- https://master.php.net/manage/user-notes.php