0
$array = [
    "2a15108c-b20d-4025-ad92-3ebfb3bb7970",
    "3a088dcd-160b-44e4-8286-f22be7703ab7",
    "5a088dcd-160b-44e4-8286-f22be7703a41",
    "9a088dcd-160b-44e4-8286-f22be7703a6f",
    "65a31a98-6666-4cb6-8a47-2b80a9c914d8",
];

I have an array, I want to move "9a088dcd-160b-44e4-8286-f22be7703a6f" from 4th in the array, to 2nd, so the expected output would be:

$array = [
    "2a15108c-b20d-4025-ad92-3ebfb3bb7970",
    "9a088dcd-160b-44e4-8286-f22be7703a6f",
    "3a088dcd-160b-44e4-8286-f22be7703ab7",
    "5a088dcd-160b-44e4-8286-f22be7703a41",
    "65a31a98-6666-4cb6-8a47-2b80a9c914d8",
];

I tried looping thru, once I found "9a088dcd-160b-44e4-8286-f22be7703a6f", I'd unset it, then array_values

array_values($uuids);

Then add "9a088dcd-160b-44e4-8286-f22be7703a6f" to the array, since I want it to be third in the list, I need to make sure it gets added after the 2nd one in the list

$uuids[1] = "9a088dcd-160b-44e4-8286-f22be7703a6f";

Which then removes: 2a15108c-b20d-4025-ad92-3ebfb3bb7970

from the array

I need to keep 2a15108c-b20d-4025-ad92-3ebfb3bb7970 and add 9a088dcd-160b-44e4-8286-f22be7703a6f after it

2
  • Are you ok with swapping or do you wish to keep the relative order for the rest of the array? Commented Sep 22, 2022 at 17:45
  • 1
    keep the relative order Commented Sep 22, 2022 at 18:07

2 Answers 2

2

Use array_splice() to remove and insert from the array.

$removed = array_splice($array, 4, 1);
array_splice($array, 2, 1, $removed);

Note that if you're moving to an index later than the original index, you'll need to subtract 1 from the destination index to adjust for the fact that the element was removed and all indexes shifted down.

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

Comments

1

The way I see it is to pull up or down the elements in between and then add your search value at the desired position.

Snippet:

<?php

function reArrange(&$array, $searchVal, $newPosition){
  for($i = 0; $i < count($array); $i++){
    if($array[ $i ] === $searchVal){
      if($i > $newPosition){
        for($j = $i - 1; $j >= $newPosition; --$j){
          $array[ $j + 1] = $array[ $j ]; 
        }
      }else{
        for($j = $i; $j < $newPosition; ++$j){
          $array[ $j ] = $array[ $j + 1 ]; 
        }
      }
     
      $array[$newPosition] = $searchVal;
      break;
    }
  }
}

Online Demo

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.