5

I'm working on a template and I need to check if something is an array. How do I do that in Twig?

I've tried

{% if my_var is iterable %}
  {% for v in my_var %}
      ...
  {% endfor %}
{% else %}
  {{ my_var }}
{% endif %}

but it always prints my_var, even when my_var is really an array, as evidenced when it prints out

Array
Array
myusername
../data/table.sqlite3
Goldentoa11
  • 1,700
  • 2
  • 17
  • 29
  • sorry 'bout my prev answer which I deleted... but you could engange in extending twig http://twig.sensiolabs.org/doc/advanced.html, you might find a way to create your own filter there. – DerStoffel Oct 31 '13 at 08:45
  • possible duplicate of [Check if variable is string or array in Twig](http://stackoverflow.com/questions/13876023/check-if-variable-is-string-or-array-in-twig) – Potherca Feb 20 '15 at 10:41

3 Answers3

4

Another way :

{% if my_var.count()>1 %}
BENARD Patrick
  • 30,363
  • 16
  • 99
  • 105
4

If you don't want to create a custom filter use iterable, as per the docs :

iterable checks if a variable is an array or a traversable object

{% if myVar is iterable %} ... {% endif %}
Raja Khoury
  • 3,015
  • 1
  • 20
  • 19
3

Just add a custom filter:

$twig->addFilter('is_array', new \Twig_Filter_Function('is_array'));

Then use it like this:

{% if my_var|is_array %}
André Figueira
  • 6,048
  • 14
  • 48
  • 62
  • When using this method, you have to use it like this: $twig->addFilter('is_array', new \Twig_Filter_Function('is_array')); Or use {% is_array(my_var) %} – kendepelchin May 21 '15 at 08:54