When developing with Craft CMS, you often encounter situations where the data type of a variable is uncertain. Whether you are dealing with dynamic Matrix blocks, complex Entry queries, or custom plugin data, knowing exactly what type of variable you are working with—be it a string, an array, a boolean, or an integer—is crucial for writing robust and error-free templates.

While PHP developers have access to functions like gettype() or is_string(), Twig handles type checking a bit differently. In this guide, we will explore the various methods available to check variable types in Craft CMS, from native Twig tests to advanced regex patterns and modern Craft 5 enhancements.

Why Variable Type Checking Matters in Craft CMS

Craft CMS is built on top of the Yii framework and uses Twig as its primary templating engine. Because Craft's data structure is so flexible, a single variable might return a String in one context (like a Plain Text field) and an ElementQuery object in another (like an Entries field).

Attempting to perform a loop on a string or a string operation on an object will result in a template error. By implementing type checks, you can create more resilient components that fail gracefully or adapt their output based on the data they receive.

1. Using Native Twig Tests

Twig provides several built-in "tests" that allow you to verify the nature of a variable. These are the most performant and standard ways to handle type checking.

Checking for Iterables (Arrays and Objects)

If you need to know if you can loop over a variable using a for loop, the iterable test is your best friend. This returns true if the variable is an array or an object that implements the Traversable interface.

{% if myVariable is iterable %}
    {# You can safely loop here #}
    {% for item in myVariable %}
        {{ item }}
    {% endfor %}
{% else %}
    {{ myVariable }}
{% endif %}

Strict Boolean Comparison

Checking for booleans can be tricky because Twig's truthiness rules might treat an empty string or a zero as false. To check specifically for a boolean type, use the same as test, which performs a strict comparison (equivalent to === in PHP).

{% if value is same as(false) or value is same as(true) %}
    <p>The variable is a boolean.</p>
{% endif %}

2. Advanced Numeric Validation with Regex

Sometimes, you need to verify if a string is actually a numeric value or a specific type of number. While Twig has a divisible by test, it can sometimes produce unexpected results with strings.

To ensure a variable is a strict integer or a floating-point number, you can use the matches operator with a regular expression. Note that in Twig, you must double-escape backslashes.

Match an Integer

To check if a variable contains only digits:

{% if var matches '/^\\d+$/' %}
    <p>This is a valid integer.</p>
{% endif %}

Match a Floating Point Number

To check for numbers that include decimals:

{% if var matches '/^[-+]?[0-9]*\\.?[0-9]+$/' %}
    <p>This is a valid float/decimal number.</p>
{% endif %}

3. Native Type Checking in Craft 5

If you have updated to the latest version of the platform, Craft 5 (and modern versions of Twig) has simplified numeric type checking significantly. You no longer need complex regex for basic number validation.

In Craft 5, you can use the following syntax directly:

{% if value is integer %}
    <span>Number: {{ value }}</span>
{% elseif value is float %}
    <span>Decimal: {{ value }}</span>
{% endif %}

This makes your templates much cleaner and easier to read for other developers on your team.

4. Using Plugins for Detailed Type Inspection

If you are debugging a complex project and need to know the exact PHP class or type of a variable, you might consider a helper plugin. A popular approach is using a tool that provides a get_type filter or an of_type test.

For example, with a type-testing plugin, you could perform checks like this:

{% set test_var = craft.entries.section('news').all() %}

{# Check if it is a specific object type #}
{% if test_var is of_type('object') %}
  <p>This is an object.</p>
{% endif %}

{# Or output the type directly for debugging #}
{{ test_var|get_type }}
{# Potential output: "array" or "object" #}

While plugins add a dependency, they are incredibly useful during the development phase to visualize exactly what Craft is passing to your templates.

Frequently Asked Questions

How do I check if a variable is null?

In Twig, you can use the null test. This is essential when checking if an optional field has been populated: {% if myVar is null %} or {% if myVar is not null %}.

Can I check for a specific Class type (e.g., is this an Entry)?

Native Twig doesn't have an instanceof test. However, in Craft CMS, you can often check the className property or use the defined test on specific methods. For a more robust solution, the instanceof check is often added via custom Twig extensions or plugins.

Why does divisible by(1) return true for strings?

Twig's divisible by test attempts to cast the input to a number. If a string is encountered, PHP's internal casting logic may evaluate it in a way that returns true, which is why using the matches operator or the Craft 5 is integer test is preferred for strict validation.

Wrapping Up

Understanding variable types is a fundamental skill for any Craft CMS developer. For most projects, the native iterable and same as tests will handle your needs. If you're working on a modern Craft 5 site, take advantage of the is integer and is float tests to keep your code clean. When in doubt, or when debugging complex data structures, don't hesitate to use a regex pattern or a dedicated debugging plugin to see exactly what is happening under the hood.

By implementing these checks, you ensure that your templates are not only functional but also resilient against unexpected data changes in the CMS backend.