Home > Archive > 2011 > April

PHP snippet: Circular shifting of an array

By Marc Ermshaus on Monday, April 25, 2011 at 9:00 am.

<?php // This code is public domain. The original author is Marc Ermshaus.

error_reporting(-1);

/**
 * Circularly shifts an array
 *
 * Shifts to right for $steps > 0. Shifts to left for $steps < 0. Keys are
 * preserved.
 *
 * @param  array $array Array to shift
 * @param  int   $steps Steps to shift array by
 * @return array Resulting array
 */
function array_shift_circular(array $array, $steps = 1)
{
    if (!is_int($steps)) {
        throw new InvalidArgumentException(
                'steps has to be an (int)');
    }

    if ($steps === 0) {
        return $array;
    }

    $l = count($array);

    if ($l === 0) {
        return $array;
    }
    
    $steps = $steps % $l;
    $steps *= -1;

    return array_merge(array_slice($array, $steps),
                       array_slice($array, 0, $steps));
}



header('content-type: text/plain');

$a = range(0, 9);

$l = count($a);

for ($i = $l * -2; $i <= $l * 2; $i++) {
    printf("% 3s  :  %s\n", $i, implode(', ', array_shift_circular($a, $i)));
}

Comments

„Keys are preserved“ No, they won't. Preserved keys would mean 1 : Array ( [9] => 9 [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 ) for a shifting of 1. The arrays are reindexed in a continuous order, like usally in PHP operations on numerically indexed arrays.

— nikosch #

Add new comment

Name*:

Please leave the following field empty:

E-Mail:

Website:

Message*:

Please use HTML for formatting. Allowed tags:
<a href="">, <blockquote cite="">, <em>, <ul>, <ol>, <li>, <pre>, <strong>, <![CDATA[ … ]]>

<p> tags will be added automatically.

All comments are published under the CC BY-SA license.