W3docs

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.

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

Example of using the exists function to check if a specific key of an array exists in Twig

{% 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 %}

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

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

Example of using the exists function to check if a key exists in an array in Twig

{% 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:

Example of using the exists function to check if a key exists in an array in an expression in Twig

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