Red
Red

Reputation: 6398

php check array index out of bounds

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.

Upvotes: 2

Views: 7626

Answers (4)

user1646111
user1646111

Reputation:

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

Upvotes: 0

Ranjith
Ranjith

Reputation: 2819

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

Upvotes: 0

Rikesh
Rikesh

Reputation: 26451

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
  }
}

Upvotes: 3

Explosion Pills
Explosion Pills

Reputation: 191799

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.

Upvotes: 0

Related Questions