Understanding and Using PHP's key() Function
This article explains PHP's key() function, its syntax, how it determines the current array pointer's key, the possible return values, and provides multiple code examples demonstrating its behavior with indexed, associative, and empty arrays.
key() Function Syntax
mixed key(array $array)The parameter $array is the array whose current element's key you want to retrieve.
How It Works
The key() function checks the position of the internal array pointer. If the pointer points to a valid element that has a key, the function returns that key.
If the pointer does not point to a valid element or the element has no key, key() returns null.
Usage Examples
Example 1
$array = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
echo key($array); // outputs: aHere key() returns the key of the first element, which is 'a'.
Example 2
$array = array('apple', 'banana', 'cherry');
echo key($array); // outputs: 0Because the array is indexed, the first element's key is 0.
Example 3
$array = array();
echo key($array); // outputs: nullAn empty array has no elements, so key() returns null.
Example 4
$array = array(1 => 'apple', 3 => 'banana', 5 => 'cherry');
echo key($array); // outputs: 1When keys are explicitly defined, the first element's key is 1.
Example 5
$array = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
echo key($array); // outputs: a
next($array);
echo key($array); // outputs: b
next($array);
echo key($array); // outputs: cThis demonstrates that key() can be used together with next() to iterate over all keys in an array.
Important Note
The key() function moves the internal array pointer. The first call points to the first element; subsequent calls point to the next element, allowing you to traverse the array's keys.
Summary
The key() function in PHP returns the key of the element currently pointed to by the array pointer. By using key(), you can retrieve each element's key for processing, whether you are iterating through an array or need a specific element's key.
PHP Learning Recommendations
Vue3+Laravel8+Uniapp Beginner to Advanced Development Tutorial
Vue3+TP6+API Social E‑commerce System Development Course
Swoole From Beginner to Master Course
Workerman+TP6 Real‑time Chat System – Limited Time Offer
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
