How to filter associative arrays using a key array in PHP?

I have associative arrays and an array of keys.

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

How do I create an associative array from the whole element $Awhere the key is in $B? In the above example, the answer should be

$C = array('a'=>'book', 'b'=>'pencil');
+5
source share
5 answers
$keys = array_keys($B);
$C = array();
foreach ($A as $key => $value)
{
  if (in_array($key, $keys))
  {
    $C[$key] = $value;
  }
}
+2
source
$keys = array_flip($B);
$C = array_intersect_key($A,$keys);
+16
source

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

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

: PHP: array_filter() ?

+3

, , $A, $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"
}
+2

, foreach .

script : 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";
+1

All Articles