Since there are a ton of ways to accomplish the desired results and so many people provided !in_array()
as an answer, and the OP already mentions the use of array_unique
, I would like to provide a couple alternatives.
Using array_diff
(php >= 4.0.1 || 5) you can filter out only the new array values that don't exist. Alternatively you can also compare the keys and values with array_diff_assoc
. http://php.net/manual/en/function.array-diff.php
$currentValues = array(1, 2);
$newValues = array(1, 3, 1, 4, 2);
var_dump(array_diff($newValues, $currentValues));
Result:
Array
(
[1] => 3
[3] => 4
)
http://ideone.com/SWO3D1
Another method is using array_flip
to assign the values as keys and compare them using isset
, which will perform much faster than in_array
with large datasets. Again this filters out just the new values that do not already exist in the current values.
$currentValues = [1, 2];
$newValues = [1, 3, 1, 4, 2];
$a = array();
$checkValues = array_flip($currentValues);
foreach ($newValues as $v) {
if (!isset($checkValues[$v])) {
$a[] = $v;
}
}
Result:
Array
(
[0] => 3
[1] => 4
)
http://ideone.com/cyRyzN
With either method you can then use array_merge
to append the unique new values to your current values.
- http://ideone.com/JCakmR
- http://ideone.com/bwTz2u
Result:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)