3

Suppose we have two arrays:

$a=array('1'=>'Apple','2'=>'Microsoft',
         '3'=>'Microapple','4'=>'Applesoft','5'=>'Softapple');
$b=array(1,3);

Where $b array represents the keys of array $a to be differentiated against.

And we expect to receive another array $c with the following values:

$c=array('2'=>'Microsoft','4'=>'Applesoft','5'=>'Softapple');

In php manual there are two functions:

array_diff($array1,$array2);    //difference of values
array_diff_key($array1,$array2);//difference of keys

But neither of the above is applicable here.

What should we do?

Edit

Thanks everyone for contribution.

I performed some benchmarks on two arrays predefined as follows:

for ($i=0; $i < 10000; $i++) {    //add 10000 values
    $a[]=mt_rand(0, 1000000); //just some random number as a value
}
for ($i=0; $i < 10000; $i++) {    //add 10000 values as keys of a
    $b[]=mt_rand(0, 1000);    
}        //randomly from 0 to 1000 (eg does not cover all the range of keys)

Each test was also taken 10000 times, the average time of Nanne's solution was:

0.013398

And the one of decereé:

0.014865

Which is also excellent.

...Unlike some other suggestion with in_array() but (that answer was deleted):

foreach ($a as $key => $value)
if (!in_array($key, $b)) 
$c[$key] = $value;

The above did 2 seconds on average. For the obvious reason that in_array() would have to loop through the $b to check whether the value existed. The above is an excellent example how not to do it! :-)

Anonymous
  • 4,692
  • 8
  • 61
  • 91

3 Answers3

12
$c = array_diff_key($a, array_flip($b));
deceze
  • 510,633
  • 85
  • 743
  • 889
3

I would just code it like:

$c = $a;
foreach ($b as $removeKey) {
    unset($c[$removeKey]);
}
Nanne
  • 64,065
  • 16
  • 119
  • 163
0

Your array $b isn't setting array keys, you are setting values.

If you were to use:

$a=array('1'=>'Apple','2'=>'Microsoft',
     '3'=>'Microapple','4'=>'Applesoft','5'=>'Softapple');
$b=array('1' => NULL ,'3' => NULL);
array_diff_key($a,$b)

You would get the result you predict.

MarkR
  • 187
  • 1
  • 9
  • It's exactly how I posted. It would be ridiculous to expect an array of nulls in productioin. – Anonymous Aug 13 '12 at 15:05
  • No it isn't, you posted array(1,3), which equates to array(0 => 1, 1 => 3);. You were setting array values not keys. – MarkR Aug 13 '12 at 15:23
  • @MarkR You're wrong. That's what he said. The values of $b are the keys to compare in $a. He never said anything about the keys of $b. – Dan Grossman Aug 13 '12 at 16:09