In an associative array comparison on two different values PHP

Compare all elements in an array by value prep_first and prep_second and when prep_first and prep_second equals other prep_second and prep_first, delete that key. Example
$array=

 Array
    (
        [0] => Array
            (
                [description] => ...
                [prof] => ...
                [risk] => high
                [prep_first] => potassium
                [prep_second] => oxygen
            )
        [1] => Array
            (
                [description] => ...
                [prof] => ...
                [risk] => high
                [prep_first] => ethanol
                [prep_second] => sodium
            )
        [2] => Array
            (
                [description] => ...
                [prof] => ...
                [risk] => high
                [prep_first] => oxygen
                [prep_second] => potassium
            )
    
    ) 

need

Array
(
    [0] => Array
        (
            [description] => ...
            [prof] => ...
            [risk] => high
            [prep_first] => potassium
            [prep_second] => oxygen
        )
    [1] => Array
        (
            [description] => ...
            [prof] => ...
            [risk] => high
            [prep_first] => ethanol
            [prep_second] => sodium
        )
)

I tried with two loops foreach, but unable to filter․ Example

$res = [];
foreach ($array as $value) {
      $first = $value['prep_first'];
      $second = $value['prep_second'];
      foreach ($array as $value1) {
        $first1 = $value1['prep_first'];
        $second1 = $value1['prep_second'];
            if ($first !== $second1 && $second !== $first1) {
                  $res[] = $val;
            }

      }
}

Thank you

>Solution :

  • Iterate over the values, saving each combination in $combinations
  • sort() the combinations so that the order is irrelevant
  • Only add combinations to $res that were not previously saved
$res = [];
$combinations = [];

foreach ($array as $value) {
    $combination = [$value['prep_first'], $value['prep_second']];
    sort($combination);

    if (!in_array($combination, $combinations)) {
        $combinations[] = $combination;
        $res[] = $value;
    }
}

Leave a Reply