Frantisek
Frantisek

Reputation: 7693

PHP - merge only keys of an array?

Let's say I have a PHP array:

$array1 = array(
   'protein' => array('PROT', 100, 150),
   'fat'     => array('FAT',  100, 250),
   'carbs'   => arary('CARBS', 10, 20)
);

$array2 = array(
   'vitaminA' => array('vitA', 1, 2),
   'vitaminB' => array('vitB', 1, 2),
   'vitaminC' => arary('vitC', 1, 2)
);

Now I want a combined array of those nutrients (something like array_merge()), but I only need the keys, not the values themselves.

So either this:

$combined = array(
   'protein' => NULL,
   'fat'     => NULL,
   'carbs'   => NULL,
   'vitaminA'=> NULL,
   'vitaminB'=> NULL,
   'vitaminC'=> NULL
);

OR

$combined = array('protein', 'fat', 'carbs', 'vitaminA', 'vitaminB', 'vitaminC');

I can do this manually with a foreach loop, but I was hoping there's a function which would make this process fast and optimized.

Upvotes: 0

Views: 1448

Answers (2)

KilZone
KilZone

Reputation: 1615

Wouldn't this do the trick?

$combined = array_merge(array_keys($array1), array_keys($array2));

This would result in your option #2.

I haven't done any benchmarks but I know that isset() is faster than in_array() in many cases; something tells me that it will be the same for isset() versus array_key_exists(). If it matters that much, you could try to use this:

$combined = array_flip(array_merge(array_keys($array1), array_keys($array2)));

Which would result in something like this:

$combined = array(
    'protein' => 1,
    'fat'     => 2,
    'carbs'   => 3,
    'vitaminA'=> 4,
    'vitaminB'=> 5,
    'vitaminC'=> 6
);

That would allow you to use isset(), e.g. option #1.

#edit I did some research on the performance of all three mentioned functions and most, if not all, case studies show that isset() is the fastest of all (1, 2); mainly because it is not actually a function but a language construct.

However do note that we now use array_flip() to be able to use isset(), so we lose quite a few microseconds to flip the array; therefore the total execution time is only decreasing if (and only if) you use isset() quite often.

Upvotes: 2

J David Smith
J David Smith

Reputation: 4810

This:

function array_merge_keys($arr1, $arr2) {
    return array_merge(array_keys($arr1), array_keys($arr2));
}

should do the trick.

Upvotes: 0

Related Questions