Jump to content

For loop through an array starting from a later index


xProteuSx

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??

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.