Search code examples
phpcontrollertwigsymfony4array-difference

How can I filter my array by elements that are present in another array


I need to filter my array by elements that are present in another array.

More in details, I have two variables (arrays) in my Controller: one contains ALL users, another - users that are participated in evaluation. What I need is the third variable/or the list in twig (array) that will contain ALL THE REST - so I can choose from them out of a dropdown list for every evaluation (names that are already in evaluation won't appear in the dropdown list).

I am wondering now what is the best approach to do this.. Should I do this in twig or in controller?

Thank you!

twig:

<select name="user" >
   {% for user in users %}
      <option value="{{ user.idUser }}" label="{{ user.name }} ">  
   {% endfor %}
</select>

controller:

    $evals = $this
        ->getDoctrine()
        ->getRepository(User::class)
        ->findUserGroups();             // this is my own function (based on SQL query) from repository that searches for those who participated in evaluation

    $users = $this
        ->getDoctrine()
        ->getRepository(User::class)
        ->findAll();                    //this is a variable that contains ALL users (including those who already participated in evaluation)

Solution

  • This would be best handled in a controller, and you can use php's array_diff to do it.

    controller:

    $evals = $this
        ->getDoctrine()
        ->getRepository(User::class)
        ->findUserGroups();
    
    $users = $this
        ->getDoctrine()
        ->getRepository(User::class)
        ->findAll();
    
    $non_evals = array_diff($users, $evals);
    

    then in twig:

    <select name="user" >
       {% for user in non_evals %}
          <option value="{{ user.idUser }}" label="{{ user.name }} ">  
       {% endfor %}
    </select>