minor #4799 [Doc] Document loose comparison in the in operator (Amoifr)

This PR was merged into the 3.x branch.

Discussion
----------

[Doc] Document loose comparison in the `in` operator

Clarifies the comparison semantics of the `in` operator in the *Containment Operators* section of `doc/templates.rst`:

- `in` uses a loose comparison (similar to `==`) for sequences, mappings, and `Traversable` objects, like PHP's `in_array()`.
- Pointer to `same as` for strict comparisons.
- Warning about boolean left operands (e.g. `true in ['foo', 'bar']` returns `true`), which surprises users.
- Note that string containment only accepts `string`, `int`, `float` on the left.

Closes #4650 (or at least the documentation half of it — the `Investigate before 4.x` label suggests the maintainers may want to revisit the actual semantics in 4.x; this PR addresses `@gorenstein`'s explicit request to "at least improve the documentation").

Commits
-------

8af8e93970 [Doc] Document loose comparison in the `in` operator
This commit is contained in:
Fabien Potencier
2026-05-14 18:42:46 +01:00
+15
View File
@@ -794,6 +794,21 @@ operand is contained in the right:
You can use this operator to perform a containment test on strings,
sequences, mappings, or objects implementing the ``Traversable`` interface.
.. note::
For sequences, mappings, and ``Traversable`` objects, ``in`` uses a loose
comparison (similar to ``==``); use :doc:`same as <tests/sameas>` for a
strict comparison. Like PHP's ``in_array()``, this can yield unexpected
results when the left operand is a boolean:
.. code-block:: twig
{# returns true because true == 'foo' under PHP loose comparison #}
{{ true in ['foo', 'bar'] }}
Containment on strings only accepts string, integer, and float operands on
the left; other types always return ``false``.
To perform a negative test, use the ``not in`` operator:
.. code-block:: twig