How to get the first and last key of PHP array?

In this tutorial, you will learn how to get the first and the last key of an array in PHP.

With the help of the following two inbuilt functions, you can get the first and last key of an array.

  1. array_key_first()
  2. array_key_last()

PHP array_key_first function

The array_key_first() function Gets the first key of an array.

<?php
$array = array("a" => "red", "b" => "green", "c" => "blue");
$first_key = array_key_first($array);

echo $first_key;
a

PHP array_key_last function

The array_key_last() function Gets the last key of an array.

<?php
$array = array("a" => "red", "b" => "green", "c" => "blue");
$last_key = array_key_last($array);

echo $last_key;
c

The above two inbuilt functions are introduced in PHP 7.3.0. But if you don’t want to use the above functions, you can do that in the following way.

<?php
$array = array("a" => "red", "b" => "green", "c" => "blue");

$keys = array_keys($array);
$first_key = $keys[0];
$last_key = end($keys);

echo "First => $first_key \n";
echo "Last => $last_key";
First => a 
Last => c

Leave a Reply

Your email address will not be published.