views:

1548

answers:

3

I have an array like the following

Array ( [0] => "txt1" [1] => "txt2" [2] => "txt3")

I have another array like it but with different content : Array ( [0] => on [2] => on)

The aim is to get a final array with the keys of the second and the content of the first, it's like merging them.

So that the final result is : Array ( [0] => "txt1" [2] => "txt3") It would be better to change the keys to 0 - 1, but that a trivial issue, let's focus on merging them one to one.

+9  A: 

The easiest way to do this is with array_intersect_key (See the PHP Docs). It grabs the values from the first array passed corresponding to the keys present in all other arrays passed.

So, your example would look like this:

$a = array(0 => "txt1", 1 => "txt2", 2 => "txt3");
$b = array(0 => 1, 2 => 1);
$c = array_intersect_key($a, $b);
print_r($c);

prints:

Array ( [0] => txt1 [2] => txt3 )

Jesse Rusak
use array_values() to reindex the resulting array
soulmerge
Thank you, this worked well!! :D
Omar Abid
+1  A: 

array_combine - Creates an array by using one array for keys and another for its values

troelskn
sizes of input arrays should be equal
SilentGhost
Ah .. I overlooked that.
troelskn
+1  A: 

why don't you use straightforward solution?

foreach($arr2 as $k=>$v) {
    $a[$k] = $arr1[$k];
}
SilentGhost
I tend to implement manual solutions like this, they work fine, but you should always assume any native function will be faster and maybe become more optimized in the future, meanwhile your foreach will always stay the same speed.
TravisO
I think if one unable to access docs by some reason, straightforward implementation is way to go. Surely buil-in function provides better performance, but it's kind of gain you can get if you know that built-in exists.
SilentGhost