user225269
user225269

Reputation: 10913

using array_intersect_key on a single array

I have an array which looks like this:

Array
(
    [0] => Array
        (
            [Binding] => Video Game
            [Brand] => Sony
            [Color] => Crystal black
            [EAN] => 0151903136010
            [Edition] => WiFi
         )
    [1] => Array(
            [Binding] => Console
            [Brand] => Nintendo
            [Color] => blk n wht
            [EAN] => 0045496880866
            [Edition] => Deluxe Set
         )

What I want to do is to be able to extract only the common keys, the value doesn't matter. The items in this array can range from 2 to 6.

It seems like array_intersect_key is the function that I'm looking for but it takes 2 or more arrays as an argument so I'll have to do something like:

$item_count = count($items);
if($item_count == 2){
  $intersection = array_intersect_key($items[0], $items[1]);
}else if($item_count == 3){
  $intersection = array_intersect_key($items[0], $items[1], $items[2]);
}

It feels like pretty tedious to do it this way. Any ideas what would be the easier and more elegant way to do this without using ifs? Thanks in advance!

Upvotes: 1

Views: 74

Answers (1)

Alma Do
Alma Do

Reputation: 37365

Use call_user_func_array():

//$array is your original array
$result = call_user_func_array('array_intersect_key', $array);

Upvotes: 2

Related Questions