dadamssg87 Posted September 18, 2012 Share Posted September 18, 2012 If i'm looping through an array how do i get the next item key. For example: $items['a'] = "One"; $items['b'] = "Two"; $items['c'] = "Three"; $items['d'] = "Four"; foreach($items as $key => $value){ $next_item = next($items); $next_key = key($next_item); echo "The current value is $value. The next key is $next_key.<br/>"; } $next_item is returned as a string. The key() function is failing. Quote Link to comment Share on other sites More sharing options...
Jessica Posted September 18, 2012 Share Posted September 18, 2012 next returns a string, not the array. What you should probably do is use array_keys and loop through that. Quote Link to comment Share on other sites More sharing options...
trq Posted September 18, 2012 Share Posted September 18, 2012 There is likely a better way. What exactly are you doing? Quote Link to comment Share on other sites More sharing options...
dadamssg87 Posted September 18, 2012 Author Share Posted September 18, 2012 pretty much exactly what i'm doing with my echo statement. I just want to get the key of the next item in the array while in the loop. Quote Link to comment Share on other sites More sharing options...
Jessica Posted September 18, 2012 Share Posted September 18, 2012 Why? Quote Link to comment Share on other sites More sharing options...
dadamssg87 Posted September 18, 2012 Author Share Posted September 18, 2012 I'm trying to create a page that has several full blog posts. Each post will be echo'ed out within a loop. I want each blog title to have an anchor next to it. Something like "<a name="post_<?=$post_id;?>" /> under each blog title i want a link that links to the next blog title "<a href="#post_<?=$next_post_id;?>">Not interested? Skip to next article.</a> Quote Link to comment Share on other sites More sharing options...
Christian F. Posted September 18, 2012 Share Posted September 18, 2012 In that case I'd actually construct the items array like this: $items = array (array ('a', 'one'), array ('b', 'two'), array ('c', 'three')); That said, you can actually increase the letters as if they were number too. So you can do this, though I wouldn't recommend it: foreach($items as $key => $value){ // Increment the key until next valid index is found. while (!isset ($items[++$key])); echo "The current value is $value. The next key is $key.<br/>"; } Quote Link to comment Share on other sites More sharing options...
Jessica Posted September 18, 2012 Share Posted September 18, 2012 What you should probably do is use array_keys() Quote Link to comment 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.