Jasir alwafaa
Jasir alwafaa

Reputation: 586

Determine new value position if values were sorted descending

How can we find key difference array using two arrays like:

First Array:

$array_1 = ['300', '200', '500'];

Second Array:

$array_2 = ['500', '300', '200'];

$array_2 is generating by applying rsort to $array_1.

Then I want to generate an array of keys by comparing value of $array_1 and key of $array_2.

Output expected:

$key_array = [1, 2, 0];

Upvotes: 0

Views: 30

Answers (2)

Barmar
Barmar

Reputation: 780879

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

Upvotes: 1

Dhara Parmar
Dhara Parmar

Reputation: 8101

Try:

$array_1 = array('300','200','500');
$array_2 = array('500','300','200');
$key_array = array();
foreach($array_1 as $arr1) {
   $key_array[] = array_search($arr1, $array_2); // get key in array_2 for value of array1
}
print_r($key_array);

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 0
)

Upvotes: 1

Related Questions