Create your own operator in Twig

Code
<?php

// creating Twig Tag as Extension
class MyTwigOperators extends Twig_Extension
{
    public function 
getName()
    {
        return 
'MyOperators';
    }
    
    public function 
getOperators()
    {
        return [
        [], 
// unary operator.
        
// binary operator
            
'isIn' => [
                
'class' => 'IsIn',
                
'precedence' => 20,
                
'associativity' => Twig_ExpressionParser::OPERATOR_LEFT,
            ],
        ]];
    }
}

class 
IsIn extends Twig_Node_Expression_Binary
{
    public function 
compile(Twig_Compiler $compiler)
    {
        
$compiler
            
->raw('(in_array(')
            ->
subcompile($this->getNode('left'))
            ->
raw(', ')
            ->
subcompile($this->getNode('right'))
            ->
raw('))')
        ;
    }

    public function 
operator(Twig_Compiler $compiler)
    {
        return 
$compiler->raw('');
    }
}

$path __DIR__ '/templates/';
$file 'operator.html.twig';

echo 
'<b>- template content:</b>' PHP_EOL;
echo 
file_get_contents($path $file) . PHP_EOL;

$loader = new Twig_Loader_Filesystem($path);
$twig = new Twig_Environment($loader);
$twig->addExtension(new MyTwigOperators());

echo 
'<b>- rendered template:</b>' PHP_EOL;
echo 
$twig->render($file);
Result
- template content:
{% set needle = "foo" %}
{% set haystack1 = ["bar","baz"] %}
{% set haystack2 = ["bar","foo","baz"] %}

haystack1:
{% if needle isIn haystack1 %}
it is in array 1
{% endif %}

haystack2:
{% if needle isIn haystack2 %}
it is in array 2
{% endif %}

- rendered template:

haystack1:

haystack2:
it is in array 2