Home > front end >  Rearrange php array, move one value from one spot to another spot in array
Rearrange php array, move one value from one spot to another spot in array

Time:09-23

$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

CodePudding user response:

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.

CodePudding user response:

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

  • Related