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

Finding the intersection of an arbitrary number (n) of arrays (n <= 6, always), PHP

I have code that for every client $client I end up with an array of business IDs $ids[]. I can have at any point in the code I can have up to 6 clients in this function, the clients are stored in their own array inside a client object.

What I am trying to figure out how to do is, without knowing how many clients are in the object at any given run of the script, how do I find the intersection of the business IDs so I can get the list of IDs that appear in ALL client records?

I know I can use array_intersect($arr1, arr2, ...) and so on, but that requires me to know beforehand which arrays I am comparing, when in this case the arrays are generated on the fly, so I can’t manually add the $id arrays to array_intersect().

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

I’m stumped to figure out how to find the intersection of all of the arrays. Is there a way to pass in a function as the argument for array_intersect()? Maybe as a closure? If so, how would I accomplish that?

>Solution :

I think you can use splat operator

<?php

$clients = [
    [1,2,3],
    [1,5,6],
    [1,7,8],
];

var_dump(array_intersect(...$clients));

array(1) {
  [0]=>
  int(1)
}
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