2

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.

4
  • 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 Commented Mar 12, 2013 at 5:27
  • See this answer, which recommends using a counter to identify the last element in the looped set. Commented Mar 12, 2013 at 5:28
  • @user1073122 its not possible in my specific requirement. Commented Mar 12, 2013 at 5: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. Commented Mar 12, 2013 at 5:33

4 Answers 4

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

1 Comment

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.
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;
  }
}
?>

1 Comment

You should check the key, not value, since the value is not necessarily unique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.