note 123886 added to ref.array

From: Date: Mon, 27 May 2019 14:27:46 +0000
Subject: note 123886 added to ref.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-211134@lists.php.net to get a copy of this message
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 ) ?> ---- Server IP: 208.43.231.9 Probable Submitter: 82.199.157.34 (proxied: 190.16.140.44) ---- Manual Page -- http://php.net/manual/en/ref.array.php Edit -- https://master.php.net/note/edit/123886 Del: integrated -- https://master.php.net/note/delete/123886/integrated Del: useless -- https://master.php.net/note/delete/123886/useless Del: bad code -- https://master.php.net/note/delete/123886/bad+code Del: spam -- https://master.php.net/note/delete/123886/spam Del: non-english -- https://master.php.net/note/delete/123886/non-english Del: in docs -- https://master.php.net/note/delete/123886/in+docs Del: other reasons-- https://master.php.net/note/delete/123886 Reject -- https://master.php.net/note/reject/123886 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#211134) next »