Foreach all except last

maybe someone know how to foreach all except one?


while($row = mysql_fetch_array($query)) {
	$drink = $row['today_drink'];
	$data[$drink][] = $row;
}
foreach ($data as $m => $news) {
	echo "{$m}<br />";
	if(end($data) === $news) {
		echo "the last one is $m";
	}
}

shows
redbull
shark
batterythe last one is battery

but i wan’t
redbull
shark
the last one is battery

$end = end($data);

foreach ($data as $m => $news) {

        if ($end != $news)
            echo "{$m}<br />";
        else
	    echo "the last one is $m";
	
}

I pulled end($data) out of the loop just for code efficiency.

Try this:


define('js', '&nbsp; &nbsp;');

$data = array
(
  'tom',
  'dick',
  'harry',
  'redbull',
  'shark',
  'battery',
  'nginx '
);
	
	
foreach ($data as $news => $m)
{
	if( 1 + $news < count($data) )
	{
		echo $news, js, count($data), js,js,"{$m}<br />";	
	}
	else
	{
		echo "the last one is $m";
	}
}

die;	

output:

0 7 tom
1 7 dick
2 7 harry
3 7 redbull
4 7 shark
5 7 battery
the last one is nginx

#not efficient but it works :slight_smile:

#2 works…
#3 too hard to understand but OK!:slight_smile:

thanks !

Arrays in PHP aren’t really arrays in the strictest sense of the term. What PHP calls arrays are called dictionaries in other languages. Your example falls apart because keys in PHP can be arbitrary. If they aren’t defined (as in your example) they are 0 indexed like arrays in all other languages. But this loop wouldn’t work with a result set from a database keyed by primary key - and it wouldn’t work with any array with string keys.

There are a couple of solutions. I consider this the most straightforward:



// Detach the last element 
$last = array_pop($data);

// Loop the others.
foreach ($data as $item) {
  echo $item."<br>";
}

// Special handling of last
echo "And the last one is {$last}";

// Reattach the last element.
array_push($last);

This works, but it’s destructive to the key data on the last element. If that isn’t acceptable this solution preserves the key data.


$i = 1;

foreach ($data as $item) {
  if ( $i != count($data) ) {
    echo $item."<br>";
  } else {
    echo "And the last one is ".$item";
  }
  $i++;
}

@wonshikee - Your example only works if the all the values are unique. It there is duplication between the last value and any of the previous both will be labeled as last.