Faster way to intersect arrays I need to intersect lots of arrays with each other. Those arrays are like:
$a = array(4 =&gt; true, 10 =&gt; true, 18 =&gt; true...);
$b = array(6 =&gt; true, 10 =&gt; true, 73 =&gt; true...);
$c = array(106 =&gt; true, 293 =&gt; true, 297 =&gt; true...);

In PHP there is a function array_intersect_key, which intersects keys; it works fine but it's not very efficient. There is also another function array_intersect, which intersects values, and is much slower than array_intersect_key because it's O (n^2) instead of O (n) (array_intersect_key).
The problem with array_intersect_key is that it does lots of pre computation before executing the intersection, like ordering the arrays, verifying data types... at every call but I don't need that because my arrays are already ordered and contain only numbers. So I came up with this function:
function array_intersect_key_custom($a,$b) {
    
    $intersection = array();
    
    foreach ($a as $chave1 =&gt; $valor1) {
    
        if (isset($b[$chave1])) {
        
            $intersection [$chave1] = true;
        
        }

    }
    
    return $intersection;

}

This function runs a little faster than any other alternative I came up, but it's still too slow. Is there any code optimization, mathematical operation, matrix operation... that I can do in order to make this code run faster?
I tried hard but I couldn't find anything faster than the native array_intersect_key. It runs 30-50% faster than your function in my tests. Tried with PHP 7.0 and this array generator for test data:
function randomArr($size, $max) {
  $res = [];
  for ($i = 0 ; $i&lt;$size; $i++) {
    $r = random_int(1, $max);
    if (!isset($res[$r])) {
      $res[$r] = true;
    }
    else {
      $i = $i-1;
    }
  }
  ksort($res);
  return $res;
} 

Try with 10 Mio entries and $max=100000000 and I'd be really surprised if your function was faster. Maybe the densitiy of your arrays plays a role?
However, I found one little optimization for your function: If you don't require the result to have the form [3 =&gt; true, 7 =&gt; true, 23 =&gt; true, ...], but you can work with [0 =&gt; 3, 1 =&gt; 7, 2 =&gt; 23, ...] as well, it's a bit faster to just push the intersection keys onto the result array: $intersection[] = $chave1;. But this only saved me at most 10%.