Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two arrays (key and content) in PHP

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.

like image 245
Omar Abid Avatar asked Dec 08 '22 08:12

Omar Abid


2 Answers

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
)
like image 71
Jesse Rusak Avatar answered Dec 21 '22 09:12

Jesse Rusak


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

like image 21
troelskn Avatar answered Dec 21 '22 08:12

troelskn