0

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 e.c.t. it varies each time.

splash58
  • 26,043
  • 3
  • 22
  • 34
Mike Abineri
  • 409
  • 2
  • 13
  • Have you searched online for a solution? https://stackoverflow.com/a/11703775/630203 – Djave Jan 11 '19 at 16:03
  • I did see array_unshift however I thought it simply added a value not moved it ? – Mike Abineri Jan 11 '19 at 16:07
  • "The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array" - this is nearly what I want however I was hoping there was a simpler solution other than using array_unshift and then removing the duplicate value. – Mike Abineri Jan 11 '19 at 16:10
  • Thank you thats a good point I wasnt very clear, I apologize for that, I have edited the post, and its not always the last element the element I want to move to the beginning each time varies in position however it does always need to be added to the beginning. – Mike Abineri Jan 11 '19 at 16:18

2 Answers2

2

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.

Kousha
  • 32,871
  • 51
  • 172
  • 296
2

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
)
Pinke Helga
  • 6,378
  • 2
  • 22
  • 42