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! :-)

3 Answers 3

12
$c = array_diff_key($a, array_flip($b));
Sign up to request clarification or add additional context in comments.

3 Comments

Oh, thanks, this is a very cute oneliner! This will be useful to many users.
This is exactly what I was after
This is just beautiful! <3
3

I would just code it like:

$c = $a;
foreach ($b as $removeKey) {
    unset($c[$removeKey]);
}

Comments

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.

3 Comments

It's exactly how I posted. It would be ridiculous to expect an array of nulls in productioin.
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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.