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');
0

5 Answers 5

20
$keys = array_flip($B);
$C = array_intersect_key($A,$keys);
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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"
}

3 Comments

Obviously wrong :/. OP need to filter an array with another, your solution doesn't. And the result in $C should be an associative array, in your solution it's an indexed one.
Edited to make $C associative
Edit: And I didn't mean to be ironic, you solution is working and is - I personnaly found - more elegant than mine.
1
$keys = array_keys($B);
$C = array();
foreach ($A as $key => $value)
{
  if (in_array($key, $keys))
  {
    $C[$key] = $value;
  }
}

Comments

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";

1 Comment

Awesome \o/ (and some more characters to reach 15).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.