Jump to content

Recommended Posts

The return from "next ( array &$array )" seems to be off and returns the end one element too soon

 

Here is my code:

 

<?php
$territory = array('North','South','East','West');
$my_territories = "";
reset($territory);
foreach ($territory as &$val) {
// also tried without the reference, but same result...
//foreach ($territory as $val) {

$my_territories .=  "$val";
    if(next($territory)){
// also tried various others but akk with the same result; like...
// if (next($territory) === FALSE) {
// if (next($territory) === end($territory)) {
        $my_territories .= ", ";
    }

}
echo "My Territories:  $my_territories";
?>

 

The output from above code is: My Territories: North, South, EastWest

 

NOTE: The missing comma between East and West

 

In other words, I'm looking for my output to be: My Territories: North, South, East, West

 

Is my logic wrong?  Is there a better way to do to this?  Or can you lead me in the right direction.  Been at this for several hours now trying various things, but can't seem to get it to work. 

 

Please let me know, thanks!

Link to comment
https://forums.phpfreaks.com/topic/266993-issue-with-next-array-array/
Share on other sites

From the PHP manual: next

next

 

next -- Advance the internal array pointer of an array

 

foreach

Note:

 

When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

 

As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.

 

Your call to next() is advancing the pointer that foreach is using. So, yes, it will screw up the process.

 

As Pikachu said, if all you need is the comma-separated list, use implode.

 

If there is more going on in that loop. I typically would use something along the lines of:

 

$my_territories .= (empty($my_territories) ? '' : ', ') . $val;

 

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.