0

i am trying to building an application in which 2 arrays is there, second array is getting applying rsort to first array.

$array_1 = array('20','30','30','20');
$array_2 = array('30','30','20','20');

i want generate a new array by searching array_1 in array_2 and return key values, ie

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

I tried like

$array_1 = array('20','30','30','20');
$array_2 = $array_1;

rsort($array_2);
$first_keys = array();
foreach($array_1 as $key=>$arr1){
    $first_keys[] = array_search($arr1, $array_2);
}
echo "<pre>";
print_r($first_keys);

but its getting 2,0,0,2

I also tried replacing current key by 'xx'.but it also printing 2,0,0,2

foreach($array_1 as $key=>$arr1){
    $array_1[$key] = 'xx';
    $first_keys[] = array_search($arr1, $array_2);
}
1
  • on what basis to get this output? I am kind of confuse Commented Aug 6, 2016 at 8:34

2 Answers 2

2

You need to remove from $array2 the value on each search, while preserving the array references. This should work (can't test here):

$array_1 = array('20','30','30','20');
$array_2 = $array_1;

rsort($array_2);
$first_keys = array();
foreach($array_1 as $key=>$arr1){
     $key= array_search($arr1, $array_2);
     $first_keys[] = $key;
     $array_2[$key]="";
}
echo "<pre>";
print_r($first_keys);
Sign up to request clarification or add additional context in comments.

1 Comment

Thnks...figure it out
1

You have to remove searched key from second array.

Unset that key from second array.(working)

$array_1 = array('20','30','30','20');

$array_2 = $array_1;

rsort($array_2);

$first_keys = array();
foreach($array_1 as $key=>$arr1){
    $searchKey = array_search($arr1, $array_2);
    $first_keys[] = $searchKey;
    unset($array_2[$searchKey]);

}
echo "<pre>";
print_r($first_keys);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.