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
<code>mixed key(array $array)</code>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
<code>$array = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
echo key($array); // outputs: a</code>Here key() returns the key of the first element, which is 'a' .
Example 2
<code>$array = array('apple', 'banana', 'cherry');
echo key($array); // outputs: 0</code>Because the array is indexed, the first element's key is 0 .
Example 3
<code>$array = array();
echo key($array); // outputs: null</code>An empty array has no elements, so key() returns null .
Example 4
<code>$array = array(1 => 'apple', 3 => 'banana', 5 => 'cherry');
echo key($array); // outputs: 1</code>When keys are explicitly defined, the first element's key is 1 .
Example 5
<code>$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: c</code>This 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
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.