0

I want to move element of array present at 1st index to the 5th index in the array. How can I do that?

2
  • Think, if you really need that Commented Jan 25, 2011 at 13:21
  • @YourCommonSense - no wonder your account is temporarily suspended. lol Commented Jun 1, 2012 at 13:56

3 Answers 3

3

Although there are currently at least 2 valid answers to the question you asked, an array is not the right the right data structure to hold a list which has frequent changes and where ordering is important. These solutions will start to get very slow as the size of the array increases.

The right structure would be linked list, unfortunately AFAIK the bundled PHP implementation (splDoublyLinkedList) does not support inserts either.

Sign up to request clarification or add additional context in comments.

Comments

2

If you really mean "move", than that can be something like this

$from = 1;
$to = 5;
$el = $array[$from];
unset($array[$from]);
$array = array_merge (
    array_slice($array,0,$to),
    array($el),
    array_slice($array,$to));

Cant test it, but the idea is: We take and remove the Element at $from from the original array, than we split the rest at $to and merge all together. Maybe some index in array_slice() does not match exactly;)

1 Comment

@Mark: I know, but associative arrays are not lists and doesn't have indexes (in the meaning of "index").
0
$arr[4]=$arr[0];
unset($arr[0]);

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.