I need to take an element from the Array and change its position within the Array by moving the rest of the elements as required.
This is the function that does it. The first parameter is the working Array. The second is the position of the element to move and the third is the position where to move the element.
The function returns the modified Array.
<?php
function array_move_elem($array, $from, $to) {
if ($from == $to) { return $array; }
$c = count($array);
if (($c > $from) and ($c > $to)) {
if ($from < $to) {
$f = $array[$from];
for ($i = $from; $i < $to; $i++) {
$array[$i] = $array[$i+1];
}
$array[$to] = $f;
} else {
$f = $array[$from];
for ($i = $from; $i > $to; $i--) {
$array[$i] = $array[$i-1];
}
$array[$to] = $f;
}
}
return $array;
}
?>
Examples:
<?php
$array = array('Cero','Uno','Dos','Tres','Cuatro','Cinco','Seis','Siete','Ocho','Nueve','Diez');
$array = array_move_elem($array, 3, 5); print_r($array);
$array = array_move_elem($array, 5, 3); print_r($array);
?>
Return:
<?php
Array ( [0] => Cero [1] => Uno [2] => Dos [3] => Cuatro [4] => Cinco [5] => Tres [6] => Seis [7] => Siete [8] => Ocho [9] => Nueve [10] => Diez )
Array ( [0] => Cero [1] => Uno [2] => Dos [3] => Tres [4] => Cuatro [5] => Cinco [6] => Seis [7] => Siete [8] => Ocho [9] => Nueve [10] => Diez )
?>