简体   繁体   中英

Moving array element to beginning of array?

If I have an array like the one below how would I go about moving key [2] and its associated value to the beginning of the array ? (making it key [0] and increasing the other keys by 1)

Current:

[0] => Array
    (
        [name] => Vanilla Coke cans 355ml x 24
    )

[1] => Array
    (
        [name] => Big Red Soda x 24
    )

[2] => Array
    (
        [name] => Reeses White PB Cups - 24 CT
    )

Desired outcome:

[0] => Array
    (
        [name] => Reeses White PB Cups - 24 CT
    )

[1] => Array
    (
        [name] => Vanilla Coke cans 355ml x 24
    )

[2] => Array
    (
        [name] => Big Red Soda x 24
    )

EDIT

To clarify I do will always want to move an element to the begining of the array but it wont necessarily be the last element it can sometimes be the 3rd 4th ect it varies each time.

Why don't you use array_unshift and array_pop together?

array_unshift($someArray, array_pop($someArray));

array_pop removes the last element, and array_shift prepends the entry to the array.

array_splice removes (and optionally replaces / inserts) values from an array returning an array with the removed items. In conjunction with the simple array_unshift function the job could be done.

$arr = [1,2,3,4,5];

function array_move_item_as_first(array $array, int $idx) : array
{
  array_unshift( $array, array_splice($array, $idx, 1)[0] );
  return $array;
}

print_r(array_move_item_as_first($arr, 2));

output:

Array
(
    [0] => 3
    [1] => 1
    [2] => 2
    [3] => 4
    [4] => 5
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM