Jump to content

For loop through an array starting from a later index


xProteuSx
 Share

Recommended Posts

I am wondering whether there is a way to do a foreach loop for an array, without starting at index[0].  Say, for example, I wanted to start displaying the contents of a 20 item array starting at index 5, what is the best way to do it?

 

I know of this way, but it seems too crude (ie. there has to be a better way):

 

$count = 0;

 

foreach($array as $item)

  {

  if ($count > 5)

    {echo $item;}

  $count++;

  }

 

Any other ideas??

Link to comment
Share on other sites

The best solution is to use special functions: http://ru.php.net/manual/en/function.end.php

 

Here is just an example how to use it

$a=array( 'a'=> 45, 'ljlsdjf', 'adjfosjf', 'cd'=>33);

echo 'Direct order<br>';
foreach( $a as $k=>$e )
{
  echo "a[$k]=$e<br>";
}

echo 'Reverse order<br>';
for( $e=end($a), $k=key( $a ); current( $a ); $e=prev( $a ), $k=key($a) )
{
  echo "a[$k]=$e<br>";
}

 

It works with any kind of keys.

 

PS. I changed a little the initial code, I've added a printout of direct order.

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.