9
{% if foo is same as('bar') %}

vs.

{% if foo == 'bar' %}

When to use first and when to use second? Does one of them has advantages over another?

2 Answers 2

14

Looking at the Twig code, they have this documented for the “same as” test:

Checks if a variable is the same as another one (=== in PHP).

I won’t re-hash the details of === vs. == in PHP because there is an excellent comparison here: https://stackoverflow.com/questions/80646/how-do-the-php-equality-double-equals-and-identity-triple-equals-comp

The money quote is:

== compares the values of variables for equality, type casting as necessary. === checks if the two variables are of the same type AND have the same value.

And here’s what the PHP docs have to say:

http://www.php.net/manual/en/language.operators.comparison.php

1

For example:

false == 0 will be true

false === 0 will be false

It is very useful when you use such functions as file_put_contents() and preg_match().

The first function returns a number of bytes writtent to the file (which can be 0 if nothing was written what does not mean that it's false). And the second one returns 1 if something was found otherwise 0.

They always warn people when you must check for the variable type too. Php.net: Go at "Return values" and you will see a red Warning block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.