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
https://forums.phpfreaks.com/topic/268486-get-next-item-key-in-array-loop/
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>

 

 

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

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.