The difference between array_diff
and array_diff_assoc
is that the second compares the index as well. In your case, how are two arrays numerical index (sometimes called sequential) where apparently no matter what index the value is. If Alexandre/65
is the first in a array and the last one on the other makes no difference, it’s the same record, so should utilise array_diff
.
However, as stated in official documentation:
Note:
Two elements are considered equal if and only if, (string) $elem1 === (string) $elem2
. In words: when the representation of string is the same.
And this is where the problem lies. Its elements are array and cannot be converted to string in this way; and that is what justifies the error message you had:
Notice: Array to string Conversion in ...
Why does language compare values like string? I don’t know, there must be some reason (or not...). To solve this you must do it manually:
$diff = [];
foreach ($array_1 as $arr) {
if (!in_array($arr, $array_2)) {
$diff[] = $arr;
}
}
print_r($diff);
With that the way out would be:
Array
(
[0] => Array
(
[nome] => Zezinha
[idade] => 29
)
[1] => Array
(
[nome] => Rosana
[idade] => 64
)
)
The function in_array
is based on the loose comparison between the elements, ==
, but you can use the restricted, ===
, if the third parameter, strict
, is defined as true.
An alternative is to manually implement the comparison function and use array_udiff
:
function compare_array($a, $b)
{
return $a <=> $b;
}
$diff = array_udiff($array_1, $array_2, 'compare_array');
The result would be the same. With anonymous function would be:
$diff = array_udiff($array_1, $array_2, function ($a, $b) {
return $a <=> $b;
});
You’re spending two arrays sequential (which have array associative) for a function that compares arrays associative. What I intended to do with this code?
– Woss
@Andersoncarloswoss want to separate the names that are not repeated, have to print Zezinha and Rosana, he does this, but from the above mistake.
– Thiago Moreira
And what to do with age? It should also be compared?
– Woss
@Andersoncarloswoss I think there is no need, because the age already comes attached to the name, so separating by name, automatically already separates the corresponding age!
– Thiago Moreira
But what if there are two Camilas with different ages?
– Woss
@Andersoncarloswoss had not thought about it! So if it is possible to compare also the same name by different age
– Thiago Moreira