note 68039 added to ref.array
| From: | nick at osu1 dot php dot net | Date: | Tue, 11 Jul 2006 12:46:21 +0000 |
| Subject: | note 68039 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-114667@lists.php.net to get a copy of this message | ||
This little function will move an array element up or down. Unlike the similar function in a
previous comment this will work for associative arrays too.
Because it uses current to traverse the array it will fail if a value is false (or 0). It could
probably be rewritten to use each() but I couldn't work it out.
<?php
function array_move_element($array, $value, $direction = 'up') {
$temp = array();
if(end($array) == $value && $direction == 'down') {
return $array;
}
if(reset($array) == $value && $direction == 'up') {
return $array;
}
while ($array_value = current($array)) {
$this_key = key($array);
if ($array_value == $value) {
if($direction == 'down') {
$next_value = next($array);
$temp[key($array)] = $next_value;
$temp[$this_key] = $array_value;
} else {
$prev_value = prev($array);
$prev_key = key($array);
unset($temp[$prev_key]);
$temp[$this_key] = $array_value;
$temp[$prev_key] = $prev_value;
next($array);
next($array);
}
continue;
} else {
$temp[$this_key] = $array_value;
}
next($array);
}
return $temp;
}
?>
----
Server IP: 83.138.144.80
Probable Submitter: 83.67.130.184
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit -- http://master.php.net/note/edit/68039
Del: integrated -- http://master.php.net/note/delete/68039/integrated
Del: useless -- http://master.php.net/note/delete/68039/useless
Del: bad code -- http://master.php.net/note/delete/68039/bad+code
Del: spam -- http://master.php.net/note/delete/68039/spam
Del: non-english -- http://master.php.net/note/delete/68039/non-english
Del: in docs -- http://master.php.net/note/delete/68039/in+docs
Del: other reasons-- http://master.php.net/note/delete/68039
Reject -- http://master.php.net/note/reject/68039
Search -- http://master.php.net/manage/user-notes.php