Move Value in PHP Array to the Beginning of the Array

前端 未结 12 1366
终归单人心
终归单人心 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:32
    $a = array('red','green', 'blue','yellow');
    
    $b = array_reverse( $a );
    

    If your question is how to make the last become the first.

    0 讨论(0)
  • 2020-12-10 03:36

    This seems like the simplest way to me. You can move any position to the beginning, not just the last (in this example it moves blue to the beginning).

    $colours = array("red", "green", "blue", "yellow");
    
    $movecolour = $colours[2];
    unset($colours[2]);
    array_unshift($colours, $movecolour);
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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 :/

    0 讨论(0)
  • 2020-12-10 03:40

    PHP: move any element to the first or any position:

    $sourceArray = array(
        0 => "red",
        1 => "green",
        2 => "blue",
        3 => "yellow"
    );
    // set new order
    $orderArray = array(
        3 => '',
        1 => '',
    );
    $result = array_replace($orderArray, $sourceArray);
    print_r($result);
    
    0 讨论(0)
  • 2020-12-10 03:41

    If you aren't always planning on bringing the very last object to the beginning of the array, this would be the most simplistic way to go about it...

    $array = array('red','green','blue','yellow');
    unset($array[array_search($searchValue, $array)]);
    array_unshift($array, $searchValue);
    
    0 讨论(0)
提交回复
热议问题