In Twig, check if a specific key of an array exists

In Twig, you can use the exists function to check if a specific key of an array exists. Here is an example:

{% if array is defined and array.key is defined %}
    The key exists in the array.
{% else %}
    The key does not exist in the array.
{% endif %}

Watch a course Learn object oriented PHP

You can also use the exists function to check if a key exists in an array:

{% if array is defined and array|exists(key) %}
    The key exists in the array.
{% else %}
    The key does not exist in the array.
{% endif %}

This function can also be used in expressions like:

{% if array is defined and array|exists(key) and array.key == 'value' %}
    The key exists and the value is 'value'.
{% endif %}