If in vs intersect

What’s the difference between doing an if in statement compared to intersect?

In the following example, I’m trying to see if a keyword exists in an array.

+++
keywords = ["Hello", "World"]
+++

{{$mykeyword := slice "Hello"}}
{{if in $mykeyword .Keywords}}true{{else}}false{{end}}

This returns false.

{{$mykeyword := slice "Hello"}}
{{if intersect $mykeyword .Keywords}}true{{else}}false{{end}}

This returns true,

Does if in not work with arrays?

I think this is covered fairly well in the documentation.

Function Returns Description
in boolean Checks if an element is in an array or slice–or a substring in a string—and returns a boolean.
intersect slice Returns the common elements of two arrays or slices.

Note that the syntax for in is:

in SET ITEM

not

in ITEM SET

So, for your example, do this:

{{ $mykeyword := "Hello" }}
{{ if in .Keywords $mykeyword }} true {{ else }} false {{ end }}
1 Like