2

I've got an string loaded from my DB, and global variable from my config.yml. I want to check if variable is a part of array given below:

app.user.role ='["1","2","3","4","5","6","7","8","9","10","11"]'

I can't change that. It have to look like this.

I was checking it like this: {% if VARIABLE in app.user.role %}

Global VARIABLE is an integer (and I can't change that)

But when for example VARIABLE = 1 my statement returns true, because in app.user.role we can find four 1 (in "1","10","11"), but i want to find it just in "1" not in "10","11".

What I want is to convert app.user.role to array or find another way to check if variable is an element of my pseudo array.

I was trying to iterate through for loop but app.user.role but app.user.role is not an array (actualy it is, but with one value ["1","2","3","4","5","6","7","8","9","10","11"]).

1
  • Your app.user.role is not an array, it's a string. That's why a simple if...in doesn't work. Commented Dec 28, 2017 at 15:35

2 Answers 2

2

The string looks like JSON. You can create a Twig Extension class and register there a function that simply returns in_array:

<?php

class MyExtension extends Twig_Extension
{
    public function getFunctions()
    {
        return [
            new Twig_SimpleFunction(
                'inarray',
                [$this, 'inArray']
            ),
        ];
    }

    /**
     * @param int $variable
     * @param string $appUserRole
     *
     * @return bool
     */
    public function inArray(int $variable, string $appUserRole): bool
    {
        return in_array($variable, json_decode($appUserRole));
    }
}

Then in the template:

{% if inarray(VARIABLE, app.user.role) %}
Sign up to request clarification or add additional context in comments.

Comments

0

Found a solution. Not the best but it works.

{% set check = '"'~VARIABLE~'"' %}
{% if check in app.user.role %}

Now it's working...

2 Comments

why don't create a helper that transform your string roles in an array then use the classical if var in varArray ?
I've just did it, app.user.role is loaded straight from session, now I transform that into array and It's working as expected

Your Answer

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