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.

4
  • Have you searched online for a solution? stackoverflow.com/a/11703775/630203 Commented Jan 11, 2019 at 16:03
  • I did see array_unshift however I thought it simply added a value not moved it ? Commented Jan 11, 2019 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. Commented Jan 11, 2019 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. Commented Jan 11, 2019 at 16:18

2 Answers 2

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
)
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! Thanks for your help.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.