xProteuSx Posted December 24, 2011 Share Posted December 24, 2011 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?? Quote Link to comment https://forums.phpfreaks.com/topic/253795-for-loop-through-an-array-starting-from-a-later-index/ Share on other sites More sharing options...
doddsey_65 Posted December 24, 2011 Share Posted December 24, 2011 $count = count($array); for($i=5; $i<$count; $i++) { echo $array[$i]; } Quote Link to comment https://forums.phpfreaks.com/topic/253795-for-loop-through-an-array-starting-from-a-later-index/#findComment-1301137 Share on other sites More sharing options...
SergeiSS Posted December 24, 2011 Share Posted December 24, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/253795-for-loop-through-an-array-starting-from-a-later-index/#findComment-1301152 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.