Rooneyl
Rooneyl

Reputation: 7902

Change array index by value and reorder

I have an array of values, something like;

$array = array(1,2,3,4); 

I want to be able to reposition an element and reorder.
Edit: To be clear on this point I don't just want to swop elements around, I want to move an element to a new place in the array and maintain the order of the other elements. For example;

// move value 3 to index[1], result
$array(1,3,2,4);
// or move value 1 to index[3], result
$array[2,3,4,1);

To make it clearer if required;

$array('alice','bob','colin','dave');
// move value 'colin' to index[1], result
$array('alice','colin','bob','dave');
// or move value 'alice' to index[3], result
$array('bob','colin','dave', 'alice');

Any ideas please.

Upvotes: 0

Views: 263

Answers (2)

ops
ops

Reputation: 2049

Try this code:

function swap_value(&$array,$first_index,$last_index){
    $save=$array[$first_index];
    $array[$first_index]=$array[$last_index];
    $array[$last_index]=$save;
    return $array;
}
$array = array(1,2,3,4); 
var_dump(swap_value($array,1,2));
var_dump(swap_value($array,0,2));

Upvotes: 1

Jack
Jack

Reputation: 1015

This is copied from another StackOverflow thread by user hakre, but this function should work:

$array = array(1,2,3,4);
function moveElement(&$array, $a, $b) {
    $out = array_splice($array, $a, 1);
    array_splice($array, $b, 0, $out);
}

moveElement($array, 3, 1); // would move the value of the element at position [3] (the number 4 in the array example) to position [1]
//would output: Array ( [0] => 1 [1] => 4 [2] => 2 [3] => 3 )

It takes in the $array array and repositions element 3 to the position of [1] in the example. Use the function arguments to move whatever element value (in the example 3) to whatever position (in the example 1) you desire.

Upvotes: 1

Related Questions