I\'m looking for a simple function to move an array element to a new position in the array and resequence the indexes so that there are no gaps in the sequence. It doesnt ne
You need to create an auxiliary variable.
moveElement($a, $i,$j)
{
$k=$a[$i];
$a[$i]=$a[$j];
$a[$j]=$k;
return $a;
}
Arrays in PHP are not actual array in the C sens but associative arrays. But the way to move a value from an index to another is quiet straight forward and is the same as in C++:
Copy the value to move to a temporary buffer, translate all the elements to crush the empty spot at the source position and in the same free up a spot on the destination position. Put the backup value in the destination spot.
function moveElement ($a , $i , $j)
{
$tmp = $a[$i];
if ($i > $j)
{
for ($k = $i; $k > $j; $k--) {
$a[$k] = $a[$k-1];
}
}
else
{
for ($k = $i; $k < $j; $k++) {
$a[$k] = $a[$k+1];
}
}
$a[$j] = $tmp;
return $a;
}
$a = array(0, 1, 2, 3, 4, 5);
print_r($a);
$a = moveElement($a, 1, 4);
echo ('1 -> 4');
print_r($a);
$a = moveElement($a, 5, 0);
echo ('5 -> 0' );
print_r($a);
Output:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
1 -> 4Array
(
[0] => 0
[1] => 2
[2] => 3
[3] => 4
[4] => 1
[5] => 5
)
5 -> 0Array
(
[0] => 5
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 1
)
You'll need to add some Exception handling to have a complete code.
Based on a previous answer. In case if you need to save key indexes of an associative array, which are could be any number or string:
function custom_splice(&$ar, $a, $b){
$out = array_splice($ar, $a, 1);
array_splice($ar, $b, 0, $out);
}
function moveElement(&$array, $a, $b) {
$keys = array_keys($array);
custom_splice($array, $a, $b);
custom_splice($keys, $a, $b);
$array = array_combine($keys,$array);
}
$s = '{
"21": "b",
"2": "2",
"3": "3",
"4": "4",
"6": "5",
"7": "6"
}';
$e = json_decode($s,true);
moveElement($e, 2, 0);
print_r($e);
Array
(
[3] => 3
[21] => b
[2] => 2
[4] => 4
[6] => 5
[7] => 6
)
Demo
A previous answer
destroys numeric indexes - makes them start from 0
.