Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

key

Returns the key of the array's current element.

Syntax

key(array|object $array): int|string|null

Parameters

ParameterTypeDescription
$arrayarray|objectThe array.

Return value

int|string|nullThe key, or `null` if the pointer is past the end.

Examples

The key of the last element:

<?php
 
$prices = ['tea' => 250, 'coffee' => 400];
end($prices);
 
echo key($prices);

Output:

coffee

Notes

array_key_last() is simpler and safer: it does not depend on the pointer position.

See also

  • current — Returns the element the array's internal pointer points to.
  • array_key_first — Returns the first key of an array.
  • array_keys — Returns all the keys of an array.

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.