Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

php array associatif move element

function moveKeyBefore($arr, $find, $move) {
    if (!isset($arr[$find], $arr[$move])) {
        return $arr;
    }

    $elem = [$move=>$arr[$move]];  // cache the element to be moved
    $start = array_splice($arr, 0, array_search($find, array_keys($arr)));
    unset($start[$move]);  // only important if $move is in $start
    return $start + $elem + $arr;
}
$arr = ['foo1'=>'bar', 'foo2'=>'buzz', 'foo3'=>'bazz'];
var_export(moveKeyBefore($arr, 'foo3', 'foo1'));
Source by codereview.stackexchange.com #
 
PREVIOUS NEXT
Tagged: #php #array #associatif #move #element
ADD COMMENT
Topic
Name
7+7 =