www.webdeveloper.com
Results 1 to 3 of 3

Thread: Start foreach with a certain array

  1. #1
    Join Date
    Jan 2010
    Posts
    4

    Start foreach with a certain array

    Hi

    I can't find a way of starting the foreach loop from a certain array, I have an array with 1000 values, and I want to start the loop with the 500th value, skipping the first 500, is this possible?

  2. #2
    Join Date
    Dec 2005
    Posts
    2,984
    For an array with numeric indices:
    PHP Code:
    foreach($array as $key => $value) {
       if(
    $key 500) { continue; }
       
    //regular foreach code goes here

    For an array where you want to start at a certain value:
    PHP Code:
    $startLoop false;
    $startValue "value of array you want to start at";
    foreach(
    $array as $key => $value) {
      if(
    $value == $startValue) { $startLoop true; }
      if(!
    $startLoop) { continue; }
       
    //regular foreach code goes here

    An alternative to both methods is to use a for loop...might be a little better because you don't have to run through the first 500 continue statements, but it may also not be because you'll have to use some other functions.

    For a numeric indexed array:
    PHP Code:
    for($i=500;$i<=sizeof($array);$i++) {
       
    //do something with the array values - $arr_value = $array[$i];

    Last edited by aj_nsc; 01-28-2010 at 04:57 PM.
    I've switched careers...
    I'm NO LONGER a scientist,
    but now a web developer...
    awesome.

  3. #3
    Join Date
    Nov 2008
    Posts
    2,477
    PHP Code:
    foreach(array_slice($array500, -1true) as $key => $value) {
        echo 
    "$key$value\n";

    You can skip the 3rd and 4th parameters for array_slice if you dont care about the keys.
    Last edited by Mindzai; 01-28-2010 at 06:07 PM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles