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); // Move element in position 3 to position 5..
print_r($array);
$array = array_move_elem($array, 5, 3); // Move element in position 5 to position 3, leaving array as it was.. ;)
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 )
?>
![Array Array](/uploads/1/3/8/1/138114434/160792706.png)
Php Array Remove
How to find sony a7ii shutter count. Arraykeyexists returns true if the given key is set in the array. Laravel frontend. Libreelec nordvpn. Key can be any value possible for an array index. Arrayreverse (PHP 4, PHP 5, PHP 7, PHP 8) arrayreverse — Return an array with elements in reverse order.