Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

key
php
array
communitycreator

What is the array key() method in PHP?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The key method is used to get the key of the element pointed by the internal pointer of the array.

In PHP, each array contains an internal pointer that points to the current element. It initially points to the first element of the array. We can move the pointer positions using methods like next, prev, etc.

Syntax

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

If an array is empty, or if the internal pointer points to an invalid position (like beyond the array length), then null is returned.

Example

<?php
$numbers = [
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4
];
echo "Current key is : ". key($numbers). "\n";
echo "Moving internal pointer forward 2 position \n";
next($numbers);
next($numbers);
echo "Current key is : ". key($numbers). "\n";
?>

In the code above:

  • We created a numbers array.

  • We printed the key of the current element pointed by the internal pointer, using the key method.

  • We used the next method two times to move the pointer position forward two positions.

  • We again printed the current key pointed by the internal pointer of the array, using the key method.

RELATED TAGS

key
php
array
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring