Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Probably the most straightforward way</p> <pre><code>array_unshift( $arr, array_pop( $arr ) ); </code></pre> <h2>EDIT</h2> <p>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 <em>only</em> works by moving the last element to the 0 index.</p> <p>This function, however, does satisfy that request</p> <pre><code>/** * 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; } </code></pre> <p>And, in usage</p> <pre><code>$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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload