Jump to content

get next item key in array loop


dadamssg87

Recommended Posts

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.

Link to comment
Share on other sites

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>

 

 

Link to comment
Share on other sites

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/>";
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.

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