Reputation: 653
I have two arrays which I am comparing. The comparison is working perfectly as follows:
$tmp = array_diff_key($arr1, $arr2);
$echo $tmp;
However, I only want to display the values that exist in array 2 that don't exist in array 1.
Edit: Ok so thank for everyone's help. How ever I am still unable to make it work.
I am now using
$tmp = array_diff($arr2, $arr1);
var_dump($tmp);
which prints out the following:
array(1) { [0]=> array(3) { [0]=> string(4) "cars" [1]=> string(4) "vans" [2]=> string(6) "people" } }
So, I'll explain a little.
Array 1 has cars, vans (this is pulled from the database).
Array 2 has cars, people (this is entered from a form).
I'm trying to only show values that are not in the database so I thought $tmp would echo just people as cars is in the database and vans is in $arr1
I hope thats clear as its even confusing me writing it ;)
If I var_dump both array individually I get
array(3) { [0]=> NULL [1]=> string(4) "cars" [2]=> string(4) "vans" } array(1) { [0]=> array(2) { [0]=> string(6) "people" [1]=> string(5) "tanks" } }
Upvotes: 1
Views: 492
Reputation: 7821
Use array_intersect
. array_intersect
gives values which are in both.
$tmp2 = array_intersect($arr1, $arr2);
var_dump($tmp2);
Edit : Misread the question. array_diff
will serve the purpose. array_diff
returns values from argument1 which are not present in the rest of the arguments.
$tmp2 = array_diff($arr2, $arr1);
var_dump($tmp2);
Edit : In your case, your $arr2
has an array inside it which has the values. So, you will need to array_diff($arr2[0], $arr1);
Here's a working fiddle.
Upvotes: 2
Reputation: 71384
If you are concerned with values and not key values, then you should just use array_diff()
. You would also need to reverse the order of the arrays in the parameters. Finally echoing an array isn't going to show you what you want, use var_dump()
. So putting it all together:
$tmp = array_diff($arr2, $arr1);
var_dump($tmp);
Upvotes: 1
Reputation: 2452
From my understanding of array_diff_key
, the function returns an array containing all the entries from argument1 whose keys are not present in any of the other arrays. So just put $arr2
into the first argument.
So your code should be:
$tmp = array_diff_key($arr2, $arr1);
$echo $tmp;
Upvotes: 1
Reputation: 3949
you can do as follows :
foreach($tmp as $key=>$value) {
if(isset($arr2[$key])) {
echo $arr2[$key];
}
}
Upvotes: 1
Reputation: 191729
$tmp = array_diff_key($arr2, $arr1);
$echo $tmp;
echo $tmp
will just output 'Array'
I think, so you probably have to loop over it (perhaps with foreach
) to display each individual value, or use var_dump
.
array_diff_key
also works with keys, array_diff
with values (you mention "values" in your question).
Upvotes: 2