ArrayContains()
Returns the position of the first element in the array that matches the item that we are searching for, or 0 if the item is not found.
ArrayContains( haystack=array, needle=object, substringMatch=boolean );
Returns: Number
Usage Notes
Lucee returns the index of the match, while ACF returns a Boolean, both of which are truthy
Examples
numbers = [ 4, 3, 2, 1 ];
dump(var=numbers, label="numbers");
<span class="nv">positionOfThree</span> <span class="o">=</span> <span class="nf">ArrayContains</span><span class="p">(</span> <span class="nv">numbers</span><span class="p">,</span> <span class="m">3</span><span class="p">);</span>
<span class="nf">echo</span><span class="p">(</span><span class="s2">"Position of 3: "</span> <span class="o">&</span> <span class="nv">positionOfThree</span> <span class="o">&</span> <span class="s2">"<br>"</span><span class="p">);</span> <span class="c">// outputs 2</span>
<span class="nv">words</span> <span class="o">=</span> <span class="p">[</span> <span class="s1">'hello'</span> <span class="p">,</span> <span class="s1">'world'</span> <span class="p">];</span>
<span class="nf">dump</span><span class="p">(</span><span class="k">var</span><span class="o">=</span><span class="nv">words</span><span class="p">,</span> <span class="nv">label</span><span class="o">=</span><span class="s2">"Words"</span><span class="p">);</span>
<span class="nv">positionOfWorld</span> <span class="o">=</span> <span class="nf">ArrayContains</span><span class="p">(</span> <span class="nv">words</span><span class="p">,</span> <span class="s1">'world'</span> <span class="p">);</span>
<span class="nv">positionOfSubstring</span> <span class="o">=</span> <span class="nf">ArrayContains</span><span class="p">(</span> <span class="nv">words</span><span class="p">,</span> <span class="s1">'el'</span><span class="p">,</span> <span class="nv">true</span> <span class="p">);</span> <span class="c">// substring matching</span>
<span class="nf">echo</span><span class="p">(</span><span class="s2">"Position of substring 'el': "</span> <span class="o">&</span> <span class="nv">positionOfSubstring</span> <span class="o">&</span> <span class="s2">"<br>"</span> <span class="p">);</span> <span class="c">// outputs 1</span>
<span class="nf">echo</span><span class="p">(</span><span class="s2">"Position of 'World': "</span> <span class="o">&</span> <span class="nv">positionOfWorld</span><span class="p">);</span> <span class="c">// outputs 2</span>
See also
- Arrays
- Compatibility / Migration with other CFML engines
- ArrayContainsNoCase()
- array.contains()
- Search Issue Tracker
- Search Lucee Test Cases (good for further, detailed examples)