Reputation: 586
I have two arrays First Array :
$array_1 = array('50','20','30');
Second Array :
$array_2 = array('50','30','20');
Second array is generating by applying rsort
to $array_1
How can i get another array of key like
$key_array = ('0','2','1');
Upvotes: 0
Views: 69
Reputation: 2156
you can use array_keys() function.
$array = array('50','30','20');
$arr_keys = array_keys($array);
Upvotes: 0
Reputation: 316969
The rsort function will reindex your array keys:
Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
You can use arsort instead to maintain index associations. Then you can simply use array_keys to get your desired result.
$unsorted = [50, 20, 30]; // array with unsorted values
$in_reverse = $unsorted; // create copy because arsort is by reference
arsort($in_reverse); // do the actual sorting
$keys = array_keys($in_reverse); // fetch the keys
print_r($keys);
will output
Array
(
[0] => 0
[1] => 2
[2] => 1
)
Upvotes: 0
Reputation: 2949
You can use arsort function instead of rsort to keep the array keys. After that you'll have the possibilty to use array_keys:
$array_1 = array('50','20','30');
$array_2 = $array_1;
arsort($array_2);
$key_array = array_keys($array_2);
Upvotes: 0
Reputation: 1561
I think you should use like this to sort with saved indexes:
$array_1 = array('50','20','30');
arsort($array_1);
$key_array = array_keys($array_1);
var_dump($key_array);
output:
array(3) { [0]=> int(0) [1]=> int(2) [2]=> int(1) }
Upvotes: 0
Reputation: 54831
Instead of rsort
use arsort
, which
Sort an array in reverse order and maintain index association.
After that - use array_keys
:
$array_1 = array('50','20','30');
arsort($array_1);
print_r(array_keys($array_1));
Upvotes: 1