In Twig, check if a specific key of an array exists
✔ Recommended Answer
Twig example:
{% if array.key is defined %} // do something{% else %} // do something else{% endif %}
Source: stackoverflow.com
Answered By: phpisuber01
In Twig, you can use the in
operator to check if a specific key exists in an array. Here's an example:
twig{% set myArray = {'foo': 'bar', 'baz': 'qux'} %} {% if 'foo' in myArray %} Key 'foo' exists in myArray. {% endif %} {% if 'nonexistent' not in myArray %} Key 'nonexistent' does not exist in myArray. {% endif %}
In this example, the in
operator is used to check if the key 'foo' exists in the myArray
array. If it does, the message "Key 'foo' exists in myArray." will be displayed.
You can also use the not in
operator to check if a key does not exist in an array, as shown in the second if
statement. If the key 'nonexistent' does not exist in myArray
, the message "Key 'nonexistent' does not exist in myArray." will be displayed.
Comments
Post a Comment