yano3nora
7/1/2017 - 8:28 AM

[php: foreach's first&last] Want to detect first & last of array in foreach loop. #php

[php: foreach's first&last] Want to detect first & last of array in foreach loop. #php

// unique array
$array = [1, 2, 3, 4, 5];
foreach ($array as $value) {
    if ($value === reset($array)) {
        // first
    }
    if ($value === end($array)) {
        // last
    }
}

// not unique
$array = [1, 2, 3, 4, 5]; // get array
reset($array);            // set pointer at first
$first = each($array);    // get first-key & first-value
end($array);              // set pointer at last
$end = each($array);      // get last-key & last-value
foreach($array as $key => $value) { /* reset() isn't required cause foreach moves the pointer first */
  if ($key === $first['key'] && $value === $first['value']) {
    // at first
  }
  if ($key === $end['key'] && $value === $end['value']) {
    // at last
  }
}