Using function array_intersect_key – PHP

  php

Q(Question):

I have a question but not a problem.

I have 2 arrays.


$array_1 = array("a", "b");
$array_2 = array("a" => "x1", "b" => "x2", "c" => "x3");

Is there php function that would return array("a" => "x1", "b" => "x2") if passed $array_1 and $array_2 or I have to write it. Looked at the manual and couldn’t find it.

Thanks

A(Answer):

you don’t need a whole new function…

array_intersect_key($array_2, array_flip($array_1));

A(Answer):

Try array_intersect_key() for this one

array array_intersect_key ( array array1, array array2 [, array …] )

array_intersect_key() returns an array containing all the values of array1 which have matching keys that are present in all the arguments.

But you will need to array_flip() $array1 to make values the key. So…

array_intersect_key($array2,array_filp($array1);

..I think

A(Answer):

@code green

I’ve tested that, it works.

A(Answer):

Excellent

Thank you

A(Answer):

Dormilich. You pipped me by one minute. But same solution.

A(Answer):

it’s the obvious solution, after all.

LEAVE A COMMENT