开发者

in foreach, isLastItem() exists?

Using a regular for loop, it's possible to comapred the current index with the 开发者_JS百科last to tell if I'm in the last iteration of the loop. Is there a similar thing when using foreach? I mean something like this.

foreach($array as $item){
  //do stuff
  //then check if we're in the last iteration of the loop
  $last_iteration = islast(); //boolean true/false
}

If not, is there at least a way to know the current index of the current iteration like $iteration = 5, so I can manually compare it to the length of the $array?


The counter method is probably the easiest.

$i = count($array);
foreach($array as $item){
  //do stuff
  //then check if we're in the last iteration of the loop
  $last_iteration = !(--$i); //boolean true/false
}


You can use a combination of SPL’s ArrayIterator and CachingIterator class to have a hasNext method:

$iter = new CachingIterator(new ArrayIterator($arr));
foreach ($iter as $value) {
    $last_iteration = !$iter->hasNext();
}


Here are a few methods for this;

$items  = ["Bhir", "Ekky", null, "Uych", "foo"=>"bar"];
$values = array_values($items);

// Bhir, Ekky, Uych, bar
foreach ($values as $i => $item) {
    print("$item");
    $next = isset($values[$i + 1]);
    if ($next) {
        print(", ");
    }
}

// Bhir, Ekky, , Uych, bar
foreach ($values as $i => $item) {
    print("$item");
    $next = array_key_exists($i + 1, $values);
    if ($next) {
        print(", ");
    }
}

// Bhir, Ekky, , Uych, bar
$i = count($values);
foreach ($items as $item) {
    print("$item");
    $next = !!(--$i);
    if ($next) {
        print(", ");
    }
}

// Bhir, Ekky, , Uych, bar
$items = new \CachingIterator(new \ArrayIterator($items));
foreach ($items as $item) {
    print("$item");
    $next = $items->hasNext();
    if ($next) {
        print(", ");
    }
}


No, you need to have a counter and know the amount of items in the list. You can use end() to get the last item in an array and see if it matches the current value in your foreach.


If you know that the values of the array will always be unique, you can compare the current $item to end($array) to know if you're at the last item yet. Otherwise, no, you need a counter.


You can get the key and the value in foreach() like this:

foreach($array as $key=>$value) { ... }

Alternatively, you could do a count() of the array so you know how many items there are and have an incrementing counter so that you know when you've reached the last item.


end($array);
$lastKey = key($array);
foreach($array as $key => $value) {
   if ($key === $lastKey) {
      // do something endish
   }
}


The valid() method says if the ArrayIterator object has more elements.

See:

$arr = array("Banana","Abacaxi","Abacate","Morango");

$iter = new ArrayIterator($arr);

while($iter->valid()){

    echo $iter->key()." - ".$iter->current()."<br/>";

    $iter->next();

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜