How to retrieve the position of an element in an array


Is there a built-in function to retrieve the position of a given string in an array?

For example

{% assign Arr_A = ‘A|B|C|D’ | split: ‘|’ %}

{% assign LetterToSearch = ‘C’ %}

=> so the result of the function should be 2 (position of ‘C’ in Arr_A)?


Hi @Bart_Verhaeghe,

There’s not really a function in Liquid for that, it seems.

But, with some tweaking, you could go for something similar to this:

{% assign my_array = "apples|oranges|peaches|plums" | split: "|" %}

{% assign value_element = 0 %}

{% input %}

{% for item in my_array %}
  {% assign value_element = value_element | plus:1 %}
  {% if == item %}
    {% break %}
  {% endif %}
{% endfor %}

test = {{ value_element }}

Could use some tweaking I think. Do you see something in this? The breaktag will stop the forloop as soon as the if-statement is done.

OK thanks Sven (you’re a genius!). I tweaked it a bit by comparing value_element with the size of the array in case the string does not appear in the array, but for the rest I copied your solution. Thanks!

1 Like