ali alwafaa ali alwafaa - 4 months ago 9
PHP Question

Create an array of key difference using two array

How can we find key deference array using two arrays like
First Array :

$array_1 = array('300','200','500');


Second Array :

$array_2 = array('500','300','200');


$array_2
is generating by applying
rsort
to
$array_1


Then i want to generate an array of key by comparing value of
$array_1
and key of
$array_2
.Output will be an array of

$key_array = ('1','2','0');

Answer

Use array_flip() on $array_2 to convert the keys to values and vice versa. Then you can easily find the original keys.

$flip_2 = array_flip($array_2);
$key_array = array_map(function($el) use ($flip_2) { return $flip_2[$el]; }, $array_1);

DEMO

Comments