Move Value in PHP Array to the Beginning of the Array

前端 未结 12 1408
终归单人心
终归单人心 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:36

    Probably the most straightforward way

    array_unshift( $arr, array_pop( $arr ) );
    

    EDIT

    Per your comment "how can I take any one subscript from the array and move it to the beginning", my answer above doesn't fully satisfy that request - it only works by moving the last element to the 0 index.

    This function, however, does satisfy that request

    /**
     * Move array element by index.  Only works with zero-based,
     * contiguously-indexed arrays
     *
     * @param array $array
     * @param integer $from Use NULL when you want to move the last element
     * @param integer $to   New index for moved element. Use NULL to push
     * 
     * @throws Exception
     * 
     * @return array Newly re-ordered array
     */
    function moveValueByIndex( array $array, $from=null, $to=null )
    {
      if ( null === $from )
      {
        $from = count( $array ) - 1;
      }
    
      if ( !isset( $array[$from] ) )
      {
        throw new Exception( "Offset $from does not exist" );
      }
    
      if ( array_keys( $array ) != range( 0, count( $array ) - 1 ) )
      {
        throw new Exception( "Invalid array keys" );
      }
    
      $value = $array[$from];
      unset( $array[$from] );
    
      if ( null === $to )
      {
        array_push( $array, $value );
      } else {
        $tail = array_splice( $array, $to );
        array_push( $array, $value );
        $array = array_merge( $array, $tail );
      }
    
      return $array;
    }
    

    And, in usage

    $arr = array( 'red', 'green', 'blue', 'yellow' );
    
    echo implode( ',', $arr ); // red,green,blue,yellow
    
    // Move 'blue' to the beginning
    $arr = moveValueByIndex( $arr, 2, 0 );
    
    echo implode( ',', $arr ); // blue,red,green,yellow
    

提交回复
热议问题