Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php – check multidimensional array for values that exists in more than 1 subarray

Following simplified multidimensional array given:

$input = Array 
(
    [arr1] => Array
        (
            [0] => JAN2016
            [1] => MAI2013
            [2] => JUN2014
        }
    [arr2] => Array
        (
            [0] => APR2016
            [1] => DEC2013
            [2] => JUN2014
        }
    [arr3] => Array
        (
            [0] => JAN2016
            [1] => MAI2020
            [2] => JUN2022
        }
)

I want to check for elements, that exists in more than 1 subarray. An ideal output would be:

$output = Array
(
    [JUN2014] => Array
        (
            [0] => arr1
            [1] => arr2
        )
    [JAN2016] => Array
        (
            [0] => arr1
            [1] => arr3
        )
)

I’m currently stucked in a nested foreach because i need to look all silblings of the outer foreach and don’t know how to accomplish that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  foreach($input as $k=>$values)
  {
      foreach($values as $value)
      {
          //check if value exists in array k+1....n
          //if true, safe to output.
      } 
  }

>Solution :

Extended solution which filters subarrays:

$newArray = [];
foreach($input as $k=>$values)
{
    foreach($values as $value)
    {
        $newArray[$value][] = $k;
    } 
}
print_r(array_filter(
    $newArray, 
    function($v) { return 1 < count($v); }
));

Sample fiddle here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading