Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get the first and last element of an array

Short answer

In a plain list the first element has index 0 and the last one is count() minus one:

<?php
 
$items = ['a', 'b', 'c'];
 
echo $items[0], "\n";
echo $items[count($items) - 1];

Output:

a
c

Any keys

When keys are not sequential or the array is associative, use array_key_first() and array_key_last():

<?php
 
$prices = ['tea' => 150, 'milk' => 90, 'bread' => 60];
 
echo $prices[array_key_first($prices)], "\n";
echo $prices[array_key_last($prices)];

Output:

150
60

Functions used in this recipe

  • count — Returns the number of elements in an array.
  • array_pop — Removes the last element of an array and returns it.

Thanks for reading!

Donate to the site — we work hard for you.