2

This is what I have tried:

foreach ($multiarr as $arr) {
   foreach ($arr as $key=>$val) {
      if (next($arr) === false) {
         //work on last key
      } else {
         //work
      }
   }
}

After taking another look, I thinknext is being used wrong here, but I am not sure what to do about it.

Is it possible to see if I'm on the last iteration of this array?

Norse
  • 5,674
  • 16
  • 50
  • 86
  • doing next() like that will simply duplicate what the foreach($arr) is doing anyways. you'll be skipping every other $key because of it. – Marc B Sep 06 '12 at 04:56

5 Answers5

4
$lastkey = array_pop(array_keys($arr));
$lastvalue = $arr[$lastkey];

If you want to use it in a loop, just compare $lastkey to $key

Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
1

You will need to keep a count of iterations and check it against the length of the array you are iterating over. The default Iterator implementation in PHP does not allow you to check whether the next element is valid -- next has a void return and the api only exposes a method to check whether the current position is valid. See here http://php.net/manual/en/class.iterator.php. To implement the functionality you are thinking about you would have to implement your own iterator with a peek() or nextIsValid() method.

Sam Grondahl
  • 2,397
  • 2
  • 20
  • 26
1

Try this:

foreach ($multiarr as $arr) {
   $cnt=count($arr);
   foreach ($arr as $key=>$val) {
      if (!--$cnt) {
         //work on last key
      } else {
         //work
      }
   }
}
khomyakoshka
  • 1,259
  • 8
  • 18
1

See below url i think it help full to you:-

How to get last key in an array?

How to get last key in an array?

Update:

<?php

$array = array(
    array(
    'first' => 123,
    'second' => 456,
    'last' => 789),
    array(
    'first' => 123,
    'second' => 456,
    'last_one' => 789),
);


foreach ($array as $arr) {

    end($arr);         // move the internal pointer to the end of the array
    $key = key($arr);  // fetches the key of the element pointed to by the internal pointer
    var_dump($key);

}

output:

string(4) "last" string(4) "last_one" 
Community
  • 1
  • 1
Abid Hussain
  • 7,724
  • 3
  • 35
  • 53
  • 2
    If you believe this is a duplicate of another question, use the Close button to link it to that duplicate, not an answer – Dan Grossman Sep 06 '12 at 05:04
1

This function (in theory, I haven't tested it) will return the last and deepest key in a multidemnsional associative array. Give I a run, I think you'll like it.

function recursiveEndOfArrayFinder($multiarr){

    $listofkeys = array_keys($multiarr);
    $lastkey = end($listofkeys);
    if(is_array($multiarr[$lastkey])){
        recursiveEndOfArrayFinder($multiarr[$lastkey]);
    }else{
    return $lastkey;
    }
}    
Austin
  • 124
  • 1
  • 9