Jump to content

Foreach: All But Last Element


nodirtyrockstar

Recommended Posts

I am trying to create a list with array elements. It should add a comma after every element except for the last. I have the following code:

 

foreach ($srch as $value) {
   $query .= "`" . $value . "`";
   if (next($srch)){
       $query .= ",";
   }
}

 

It is adding a comma after everything except for the LAST TWO elements. Can someone help me understand this? I have read the php.net manual about next() and it seems like it should work for this purpose.

 

Also, I realize there are other ways to do this, but right now I would really like to understand next().

Link to comment
https://forums.phpfreaks.com/topic/270097-foreach-all-but-last-element/
Share on other sites

foreach does odd things with the internal array pointer.  As such you shouldn't really mess with it when your looping your array. Either put your strings in their own array and implode() it or use trim() to remove the last comma.

 

To be somewhat more precise about what happens to the pointer, foreach() resets the pointer to the beginning of the array before it executes, and at some point the pointer gets advanced once more prior to running your first iteration of the loop.  So on your first iteration the pointer is at element [1] which means if you call next() each iteration you're going to hit the end of the array in your second to last iteration, not the last one.

 

Note this behavior of what foreach() does with the pointer is not something that you should rely upon.  If PHP ever updates how it processes a foreach() the behavior may change.

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.