Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_key_first

Returns the first key of an array.

Syntax

array_key_first(array $array): int|string|null

Parameters

ParameterTypeDescription
$arrayarrayThe source array.

Return value

int|string|nullThe first key, or `null` for an empty array.

Examples

The first and the last key:

<?php
 
$prices = ['tea' => 250, 'coffee' => 400, 'juice' => 180];
 
echo array_key_first($prices), ' ', array_key_last($prices);

Output:

tea juice

The last element of a list without changing the array:

<?php
 
$numbers = [10, 20, 30];
 
echo $numbers[array_key_last($numbers)];

Output:

30

Notes

The companion array_key_last() returns the last key. Neither modifies the array, unlike array_shift() and array_pop().

See also

  • array_keys — Returns all the keys of an array.
  • array_pop — Removes the last element of an array and returns it.

In the tutorial

  • Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.

Thanks for reading!

Donate to the site — we work hard for you.