Move Value in PHP Array to the Beginning of the Array

前端 未结 12 1410
终归单人心
终归单人心 2020-12-10 02:52

I have a PHP array similar to this:

0 => \"red\",
1 => \"green\",
2 => \"blue\",
3 => \"yellow\"

I want to move yellow to index

12条回答
  •  没有蜡笔的小新
    2020-12-10 03:40

    EDITED

    This is an update based on the question and liking the generic aspects of the answer by Peter Bailey. However, the code is too function/memory intensive for me so below just does a simple swap of the $from and $to values. This method does not cause the array in question to be resized at all, it simply swaps to values within it.

    Second Edit: I added in some more argument checking as mentioned in the comments.

    function moveValueByIndex( array $array, $from=null, $to=null )
    {
      // There is no array, or there are either none or a single entry
      if ( null === $array || count($array) < 2 )
      {
        // Nothing to do, just return what we had
        return $array;
      }
    
      if ( null === $from )
      {
        $from = count( $array ) - 1;
      }
    
      if ( null === $to )
      {
        $to = 0;
      }
    
      if ( $to == $from )
      {
        return $array;
      }
    
      if ( !array_key_exists($from, $array) )
      {
        throw new Exception( "Key $from does not exist in supplied array." );
      }
    
      $value = $array[$from];
      $array[$from] = $array[$to];
      $array[$to] = $value;
    
      return $array;
    }
    

    Forgive me if I should have just added this in a comment to Peter's post.. it just was too long to inline all of this there :/

提交回复
热议问题