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().

Edited by nodirtyrockstar
Link to comment
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.

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.