Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersect two arrays with Twig

I have two arrays which i'd like to intersect. I got these two arrays:

{{ dump(array1) }}

array(6) {
  [0]=>
  array(2) {
    ["id"]=>
    int(121)
    ["text"]=>
    string(3) "uno"
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(122)
    ["text"]=>
    string(3) "dos"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(123)
    ["text"]=>
    string(4) "tres"
  }
  [3]=>
  array(2) {
    ["id"]=>
    int(124)
    ["text"]=>
    string(6) "cuatro"
  }
  [4]=>
  array(2) {
    ["id"]=>
    int(125)
    ["text"]=>
    string(5) "cinco"
  }
  [5]=>
  array(2) {
    ["id"]=>
    int(126)
    ["text"]=>
    string(4) "seis"
  }
}

{{ dump(array2) }}

array(3) {
  [0]=>
  array(2) {
    ["id"]=>
    int(124)
    ["text"]=>
    string(6) "cuatro"
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(125)
    ["text"]=>
    string(5) "cinco"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(126)
    ["text"]=>
    string(4) "seis"
  }
  [3]=>
  array(2) {
    ["id"]=>
    int(127)
    ["text"]=>
    string(5) "siete"
  }
}

And i want my third array to have a result like this:

array(3) {
  [0]=>
  array(2) {
    ["id"]=>
    int(124)
    ["text"]=>
    string(6) "cuatro"
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(125)
    ["text"]=>
    string(5) "cinco"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(126)
    ["text"]=>
    string(4) "seis"
  }
}

The question is: How do I intersect them using a simple filter in twig?

like image 679
tblancog Avatar asked Jan 25 '26 17:01

tblancog


1 Answers

for anyone ending up here and having a sane use case and looking for an actual solution... ;)

The Twig array filter filter combined with x in array_y should get you there (added in Twig 1.41 and 2.10):

{% set arr_a = ['lemon', 'apple', 'peach', 'banana', 'orange', 'pear'] %}
{% set arr_b = ['mango', 'peach', 'orange', 'lemon', 'melon'] %}

{{ arr_a | filter((fruit) => fruit in arr_b) | join(', ') }}

lemon, peach, orange

Twig fiddle here

like image 151
7ochem Avatar answered Jan 28 '26 08:01

7ochem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!