0

I have an indexed array as follows

$item = array("one", "two", "three", "four");

I need to change the index of this array with another array

$indexarray = array("2", "0", "3", "1");

assign new index to $item array like this,

one ---> 2
two ---> 0
three ---> 3
four ---> 1

Required result:

$item = array("two", "four", "one", "three");
1
  • Is this array("2","0","3","1"); or array(2,0,3,1); ? Commented Mar 2, 2015 at 10:35

5 Answers 5

3
Use:

$c=array_combine($indexarray ,$item );
print_r($c);
Sign up to request clarification or add additional context in comments.

Comments

1

Use this

$indexarray = array("2","0","3","1");
$item = array("one","two","three","four");
$result=array_combine($indexarray ,$item );
print_r($result);

Comments

0
<?php    
    $item = array("one","two","three","four");
    $indexarray = array("2","0","3","1");
    $item_new=array();
    foreach($indexarray as $key=>$value)
    {
        $item_new[$key]=$item[$value];
    }
    $item=$item_new;
    print_r($item);
?>

3 Comments

The upper solutions are not giving the desired result as u written?
While this answer is probably correct and useful, it is preferred if you include some explanation along with it to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked.
as i understand @johnson wants to show the array "item" in order of values defined in array "indexarray". So first item array after updation will be $item[2], $item[0], $item[3], $item[1]. Let me know if i m wrong
0

First combine both arrays

$item = array("one","two","three","four");
$indexArray = array("2","0","3","1");

$tempArray = array_combine($indexArray, $item);

Then sort the array

ksort($tempArray);

Comments

0

To not only assign the desired indexes, but also reposition the elements in accordance with the new indexes, just use array_multisort() -- this task is exactly why it was invented. Demo

$item = ["one", "two", "three", "four"];
$indexarray = ["2", "0", "3", "1"];
array_multisort($indexarray, $item);
var_export($item);

Output:

array (
  0 => 'two',
  1 => 'four',
  2 => 'one',
  3 => 'three',
)

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.