note 68039 deleted from ref.array by levim
| From: | levim@php.net | Date: | Tue, 06 May 2014 22:06:34 +0000 |
| Subject: | note 68039 deleted from ref.array by levim | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-199458@lists.php.net to get a copy of this message | ||
Note Submitter: nick
----
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;
}
?>