Search code examples
phparraysforeach

Print a flat array with one value removed in a loop


How do I include the same array inside foreach loop and remove the same value inside another array. My PHP skills is not strong and I would like to seek help from the experts here. Please see the scenario below.

$array = array("group1","group2","group3","group4");
//Result should be
group1 = group2,group3,group4
group2 = group1,group3,group4
group3 = group1,group2,group4
group4 = group1,group2,group3

I am only at:

 $array = array('group1','group2','group3','group4');


foreach($array as $value){
  echo '<br>'.$prodfilters.'= <br>';
  foreach($arrayFilter as $xx){
    echo $xx.'<br>';
  }
}
//Result
group1 = group1,group2,group3,group4
group2 = group1,group2,group3,group4
group3 = group1,group2,group3,group4
group4 = group1,group2,group3,group4
//basically repeating itself each value from the outer foreach loop instead of removing the same value from the inner foreach loop.

Solution

  • Here is a short solution using array_walk and array_diff functions:

    $array = ["group1","group2","group3","group4"];
    $result = [];
    
    array_walk($array, function($v) use(&$result, $array){
        $result[$v] = array_diff($array, [$v]);   // it can be imploded into a string if needed
    });
    
    print_r($result);
    

    The output:

    Array
    (
        [group1] => Array
            (
                [1] => group2
                [2] => group3
                [3] => group4
            )
    
        [group2] => Array
            (
                [0] => group1
                [2] => group3
                [3] => group4
            )
    
        [group3] => Array
            (
                [0] => group1
                [1] => group2
                [3] => group4
            )
    
        [group4] => Array
            (
                [0] => group1
                [1] => group2
                [2] => group3
            )
    )
    

    Now you can access each item by specifying its "name" as an array key, like $result['group3']