esedic
3/5/2015 - 1:34 PM

Get first and last element in PHP array

Get first and last element in PHP array

<?php 

/*
* if  array has unique array values
*/
$cars = array("Volvo", "BMW", "Toyota");
foreach($cars as $car) {
  if ($car === reset($cars)) {
    echo '<p>FIRST ELEMENT is: '. $car .'</p>';
  }
  if ($car === end($cars)) {
    echo '<p>LAST ELEMENT is: '. $car .'</p>';
  }
}

/*
* This works if last and first elements are appearing just once in an array, otherwise you get false positives.
* Therefore, you have to compare the keys (they are unique for sure).
*/
foreach($cars as $car => $element) {
  reset($cars);
  if ($car === key($cars))
    echo '<p>FIRST ELEMENT is: '. $car .'</p>';

  end($cars);
  if ($car === key($cars)) {
    echo '<p>LAST ELEMENT is: '. $car .'</p>';
  }
}

/*
* If you are concerned about performance and/or modifying the array pointer inside a foreach loop, 
* you can cache the key value before the loop.
*/
reset($cars);
$first = key($cars);
foreach($cars as $car => $element) {
  if ($car === $first) {
    echo '<p>FIRST ELEMENT is: '. $car .'</p>';
  }
}
?>