9

I have an associative arrays and an array of keys.

$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');

How I build an associative array from all element of $A where the key is in $B? For the example above, the answer should be

$C = array('a'=>'book', 'b'=>'pencil');
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Lhuqita Fazry
  • 291
  • 4
  • 12

5 Answers5

19
$keys = array_flip($B);
$C = array_intersect_key($A,$keys);
Jon Page
  • 476
  • 3
  • 7
4

array_intersect_key($A,array_combine($B,$B))

or better: array_intersect_key($my_array, array_flip($allowed))

from the question: PHP: How to use array_filter() to filter array keys?

Community
  • 1
  • 1
Simon Elliston Ball
  • 4,375
  • 1
  • 21
  • 18
2

Here's a simple solution which checks that the key exists in $A before appending it to $C

$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');

$C = array();
foreach ($B as $bval) {
  // If the $B key exists in $A, add it to $C
  if (isset($A[$bval])) $C[$bval] = $A[$bval];
}

var_dump($C);

// Prints:
array(2) {
  ["a"]=>
  string(4) "book"
  ["b"]=>
  string(6) "pencil"
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
1
$keys = array_keys($B);
$C = array();
foreach ($A as $key => $value)
{
  if (in_array($key, $keys))
  {
    $C[$key] = $value;
  }
}
Clement Herreman
  • 10,274
  • 4
  • 35
  • 57
1

To my immense surprise, the foreach loop method is faster.

The following quick benchmark script gives me results: array_intersect_key: 0.76424908638 foreach loop: 0.6393928527832

$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');

$start = microtime(true);
for ($i = 0 ; $i < 1000000; $i++) {
$c = array_intersect_key($A,array_flip($B));
}

$t1 = microtime(true);

for ($i = 0; $i < 1000000; $i++) {
$C = array();
    foreach ($B as $bval) {
          // If the $B key exists in $A, add it to $C
          if (isset($A[$bval])) $C[$bval] = $A[$bval];
    }
}

$t2 = microtime(true);
echo "array_intersect_key: " . ($t1 - $start), "\n";
echo "foreach loop: " . ($t2 - $t1), "\n";
Simon Elliston Ball
  • 4,375
  • 1
  • 21
  • 18