Jump to content

issue with "next ( array &$array )"


gtoerner

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;

 

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.