1

Consider the following array.

$a['a'] = 1;
$a['b'] = 2;
$a['c'] = 3;
$a['d'] = 4;

and then i am looping the array

foreach( $a as $q => $x )
{

  # Some operations ....

  if( isLastElement == false  ){ 
     #Want to do some more operation
  }
}

How can i know that the current position is last or not ?

Thanks.

Red
  • 6,230
  • 12
  • 65
  • 112
  • 1
    As your array is not a numeric indexed array, you could use an integer, which is incremented and compared to the `count` of your array – MatRt Mar 12 '13 at 05:27
  • See [this answer](http://stackoverflow.com/questions/1070244/how-to-determine-the-first-and-last-iteration-in-a-foreach-loop#1070256), which recommends using a counter to identify the last element in the looped set. – George Cummins Mar 12 '13 at 05:28
  • @user1073122 its not possible in my specific requirement. – Red Mar 12 '13 at 05:31
  • 2
    What is not possible ? `count($a)` will return the number of element in your array, so you can use an integer initialized to 0 before the loop increment it at each loop, and compare it with the count of the array. You will be able to know when you are on the last element. – MatRt Mar 12 '13 at 05:33

4 Answers4

3

Take a key of last element & compare.

$last_key = end(array_keys($a));

foreach( $a as $q => $x )
{
 # Some operations ....
 if( $q == $last_key){ 
     #Your last element
  }
}
Rikesh
  • 26,156
  • 14
  • 79
  • 87
0
foreach (array_slice($a, 0, -1) as $q => $x) {

}
extraProcessing(array_slice($a, -1));

EDIT:

I guess the first array_slice is not necessary if you want to do the same processing on the last element. Actually neither is the last.

foreach ($a as $q => $x) {

}
extraProcessing($q, $x);

The last elements are still available after the loop.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0

You can use the end() function for this operation.

George Cummins
  • 28,485
  • 8
  • 71
  • 90
Ranjith
  • 2,779
  • 3
  • 22
  • 41
  • The `end()` call would have to go outside the loop as it gets the last value and sets the internal pointer to it rather than checking for it. – Paul Mar 12 '13 at 05:38
0
<?php
$a['a'] = 1;
$a['b'] = 2;
$a['c'] = 3;
$a['d'] = 4;

$endkey= end(array_keys($a));

foreach( $a as $q => $x )
{

  # Some operations ....

  if( $endkey == $q  ){ 
     #Want to do some more operation
     echo 'last key = '.$q.' and value ='.$x;
  }
}
?>