0

what would be a fast and least expensive way to check the values in an array to see if all the values exist.

Lets say that I have an array

$a = array(1,2,3,4,5,6);

I want to match it against arrays

 $b = array(6,5,1,3,2,4)
    $c = array(1,9,2,3,4,5)
    $d = array(6,5,4,3,2,1)
    $e = array(1,2,3,4,5,6,7)
    $f = array(2,3,4,1,5,6)
    .....
etc, etc

In above $a will match $b and $f, since the values are same, though not at same index.

Now I know that I can use foreach/in_array/array_search etc etc and go iterate through each one of the loops and try to get match the values. That could become very expensive very fast, if the array size increases and the amount of arrays we have. I could potentially have 1 million to 2 million + of those arrays and then looping over those in the above mentioned fashion would be a performace nightmare.

My question is what is the best way to achieve this goal. How would you guys go about it? Any ideas would be helpful. thanks

EDIT As I mentioned in my comments below, I am not looking for an answer that was given in the question thought to be duplicate. I want to have O(1) solution and not n^2. The solution there would not help me. I think I will need to have divide this properly or sub bucket the arrays etc. Imagine 1-2 million arrays, now imagine 300 million of those arrays. That solution will not scale.

Asim Zaidi
  • 27,016
  • 49
  • 132
  • 221

1 Answers1

0

I think this function help you:

array_intersect($array1, $array2); or array_diff($array1, $array2)

and count($array2)

On next step you can watch if it is empty or with elements.

Also you can check performance with:

$start = microtime(true);
// Your script goes here
$end = microtime(true);
$time = number_format(($end - $start), 11);
echo 'This page loaded in ', $time, ' seconds';
Maris
  • 390
  • 2
  • 14
  • yea thats the solution I added in my comment above, but that still does not help me with an idea of how to not do it so bruteforce. I was hoping on something like divide and conquer etc – Asim Zaidi Feb 12 '15 at 08:49
  • I didn't see your solution, i figure out it self. – Maris Feb 12 '15 at 08:50
  • any how, I edited the question. Your solution will not scale for me – Asim Zaidi Feb 12 '15 at 08:54
  • Maybe you this topic will help you http://stackoverflow.com/questions/2479963/how-does-array-diff-work – Maris Feb 12 '15 at 09:15