Avoid duplicate entries when programmatically adding field values This pretty cool answer taught me to push new term references like this:

$node-&gt;field_tags[] = 6;


... but if that reference already exists you get a duplicate.

This isn't possible through the UI and isn't what you would usually want. The duplicates show up in the rendered view.

Here's the horrible thing I did to check for the reference I'm trying to add:

$term_refs = $node-&gt;field_tags-&gt;getValue();    
$has_ref = count(array_filter($term_refs, function ($term_ref) use($tid) {
return in_array($tid, $term_ref);
  }));
if (!$has_ref) $node-&gt;field_tags[] = $tid;


Is there a hasValue() method or magic PHP function I'm missing that I can use instead?

The structure of $term_refs (the field_tags value) looks like this:

Array
(
    [0] =&gt; Array
        (
            [target_id] =&gt; 6
        )

)


Update: Clive's solution is what I'm looking for but I couldn't get this to work. So I modified George's answer to this so I can skip existing refs:

if (in_array($tid, array_map(function ($i) { return $i['target_id']; }, $term_refs))) continue;
array_unique could solve your problem here, perhaps employing a similar solution to the one proposed in https://stackoverflow.com/questions/10408482/how-to-get-unique-value-in-multidimensional-array