Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

PHP array rotation

Here are some functions to change positions of elements values in array, without changing their order, thus making array rotate. These functions do not preserve array keys, only rotating values.

This function rotates array values by specified amount of steps. Positive number will make array rotate forward, negative - backward:

<?php

$weekdays = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

function rotate_array($steps, $arr)
{
    if($steps >= 0)
    {
        for($i = 0; $i < $steps; $i++)
        {
            $elm = array_shift($arr);
            array_push($arr, $elm);
        }
    }
    else
    {
        for($i = 0; $i > $steps; $i--)
        {
            $elm = array_pop($arr);
            array_unshift($arr, $elm);
        }
    }
    return $arr;
}

$arr = rotate_array(-2, $weekdays);

echo "<pre>";
print_r($arr);
echo "</pre>";
?>

Next function will make element with specified key as first and accordingly rotate other elements:

<?php

$weekdays = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

function make_first_by_key($key, $arr)
{
    foreach($arr as $arrkey => $value)
    {
        if($arrkey != $key)
        {
            $elm = array_shift($arr);
            array_push($arr, $elm);
        }
        else
        {
            break;
        }
    }
    return $arr;
}

$arr = make_first_by_key(2, $weekdays);

echo "<pre>";
print_r($arr);
echo "</pre>";
?>

And this function does pretty same as previous, only now element is found by value:

<?php

$weekdays = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

function make_first_by_value($val, $arr)
{
    $start_key = array_search($val, $arr);
    $flip = array_flip($arr);
    foreach($arr as $key => $value)
    {
        if($start_key != $key)
        {
            $elm = array_shift($flip);
            $flip[$value] = $elm;
        }
        else
        {
            break;
        }
    }
    $arr = array_flip($flip);
    return $arr;
}

$arr = make_first_by_value("Sat", $weekdays);

echo "<pre>";
print_r($arr);
echo "</pre>";
?>

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus