Move an array element to a new index in PHP

后端 未结 9 1864
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 04:47

I\'m looking for a simple function to move an array element to a new position in the array and resequence the indexes so that there are no gaps in the sequence. It doesnt ne

9条回答
  •  我在风中等你
    2020-12-03 05:00

    May be I'm wrong but shouldn't it be easier just to make a copy of the array and then replace the values?

    function swap($input, $a, $b){
      $output = $input;
      $output[$a] = $input[$b];
      $output[$b] = $input[$a];
      return $output;
    }
    
    $array = ['a', 'c', 'b'];
    $array = swap($array, 1, 2);
    

提交回复
热议问题