1

I want to tell my array to start from key position 2 and then loop through the entire array, including the values before key position 2. I just want to use one array and specify the key position I start looping from. For example, here I am using array_splice, but it does not do what I want it to, could you help me please?

$names = array('Bill', 'Ben', 'Bert', 'Ernie');
foreach(array_slice($names, 2) as $name){
   echo $name;
}

foreach(array_slice($names, 3) as $name){
   echo $name;
}
1
  • So you don't want to use foreach but for Commented Dec 10, 2012 at 15:30

2 Answers 2

3

If the keys are irrelevant, you can splice the array twice, and merge the resulting arrays, like this:

$names = array('Bill', 'Ben', 'Bert', 'Ernie');
$start = 2;

foreach( array_merge( array_slice($names, $start), array_slice( $names, 0, $start)) as $name){
   echo $name;
}

You can see from the demo that this prints:

BertErnieBillBen

Alternatively, for efficiency, you can use two loops that are aware of wrapping around to the beginning, which will be more efficient since you are operating on the original array and not creating copies of it.

$start = 2;
for( $i = $start, $count = count( $names); $i < $count; $i++) {
    echo $names[$i];
}
$i = 0;
while( $i < $start) { 
    echo $names[$i++];
}

You could also turn this into one single loop, and just encapsulate the logic for wrapping around inside the for.

Sign up to request clarification or add additional context in comments.

Comments

0
$limit = 2; //so you can set your start index to an arbitrary number
$fn= function($a,$b) use ($limit){
  if(($a < $limit && $b < $limit) 
      || ($a >= $limit && $b >=$limit)) //$a and $b on the same side of $limit
        return $a < $b ? -1 : ($a==$b ? 0 : 1);
  if($a < $limit && $b > $limit) return 1; //because $a will always be considered greater
  if($a >= $limit && $b < $limit) return -1; //because $b will always be considered greater

};
uksort($arr, $fn);
foreach($arr as $v) echo $v;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.