b1919676 b1919676 - 5 days ago 6
PHP Question

PHP circular loop through array from n to n-1 element

Let's say I have this array:

$myArray = array(a, b, c, d, e, f, g);


And I have a start indicator,
$startpos
, whose possible value can be any value from 0 to myArray's number of elements.

So if
$startpos = 0
, the desired print result would be
a, b, c, d, e, f, g


if
$startpos = 2
, the desired print result would be
c, d, e, f, g, a, b


if
$startpos = 5
, the desired print result would be
f, g, a, b, c, d, e


I've been searching a php built-in or custom function through SO (similar question at Treat an array as circular array when selecting elements - PHP) and having a look to http://www.w3schools.com/php/php_ref_array.asp but I'm not getting the desired result. Anyone could please give me a suggestion?

Answer

You could use array_slice function with array_merge function as following :

$myArray = array('a', 'b', 'c', 'd', 'e', 'f', 'g');
$startpos = 2;


$output = array_merge(
                 array_slice($myArray,$startpos),
                 array_slice($myArray, 0, $startpos)
                    ); 
var_dump($output);

output:

array(7) {
  [0]=>
  string(1) "c"
  [1]=>
  string(1) "d"
  [2]=>
  string(1) "e"
  [3]=>
  string(1) "f"
  [4]=>
  string(1) "g"
  [5]=>
  string(1) "a"
  [6]=>
  string(1) "b"
}
Comments