The Wayback Machine - https://web.archive.org/web/20240911020640/https://www.geeksforgeeks.org/php-key-function/
Open In App

PHP key() Function

Last Updated : 20 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The key() function is an inbuilt function in PHP which is used to return the index of the element of a given array to which the internal pointer is currently pointing. The current element may be starting or next element which depends on the cursor position. By default cursor position is at zero index i.e, at starting element of the given array.

Syntax:

key($array)

Parameters: This function accepts a single parameter $array. It is the array for which we want to find the current element pointed by the internal pointer.

Return Value: It returns the index of current element of the given array. If the input array is empty then the key() function will return NULL.

Below programs illustrate the key() function in PHP:

Program 1:




<?php
  
// input array 
$arr = array("Ram", "Geeta", "Shita", "Ramu");
  
// Here key function prints the index of 
// current element of the array.
echo "The index of the current element of".
                    " the array is: " . key($arr);
                      
?>


Output:

The index of the current element of the array is: 0

Program 2:




<?php
  
// input array 
$arr=array("Ram", "Geeta", "Shita", "Ramu");
  
// next function increase the internal pointer
// to point next to the current element.
next($arr);
  
// Here key function prints the index of 
// the current element of the array.
echo "The index of the current element of".
                " the array is: " . key($arr);
                  
?>


Output:

The index of the current element of the array is: 1

Program 3:




<?php
  
// input array 
$arr = array("0", "F", "D", "4");
  
// using next() function to increment
// internal pointer two times
next($arr);
next($arr);
  
// Here key function prints the index of
// element of the current array position.
echo "The index of the current element of".
                " the array is: " . key($arr);
                  
?>


Output:

The index of the current element of the array is: 2

Reference:
http://php.net/manual/en/function.key.php



Previous Article
Next Article

Similar Reads

How to make a key fire when key is pressed using JavaScript ?
In JavaScript, holding down a key will fire the key continuously until it is released. This behavior may be used in applications such as games where a key may be expected to fire only once even after being held down. This can be achieved using two methods: Method 1: Using a flag variable to check the current key status: A flag variable is defined w
3 min read
How to Merge Child Object Value to Parent Key Based on Key Name in JavaScript ?
JavaScript allows us to merge values from child objects into their parent object based on a specific key name. This can be useful for organizing data or simplifying complex structures. There are several approaches available in JavaScript to merge child object values to parent key based on the key name which are as follows. Table of Content Using fo
4 min read
PHP SplDoublyLinkedList key() Function
The SplDoublyLinkedList::key() function is an inbuilt function in PHP which is used to return the index of the current node. Syntax: mixed SplDoublyLinkedList::key( void ) Parameters: This function does not accepts any parameters. Return Value: It returns the index of current node. Below programs illustrate the SplDoublyLinkedList::key() function i
1 min read
PHP SplObjectStorage key() Function
The SplObjectStorage::key() function is an inbuilt function in PHP which is used to get the index of the currently pointing iterator. Syntax: int SplObjectStorage::key() Parameters: This function does not accept any parameter. Return Value: This function returns the index at which the iterator currently pointing. Below programs illustrate the SplOb
1 min read
PHP SplFixedArray key() Function
The SplFixedArray::key() function is an inbuilt function in PHP which is used to get the key of the current index of the array. Syntax: int SplFixedArray::key() Parameters: This function does not accept any parameter. Return Value: This function returns the key of the current index of the array. Below programs illustrate the SplFixedArray::key() fu
1 min read
PHP | SimpleXMLIterator key() Function
The SimpleXMLIterator::key() function is an inbuilt function in PHP which is used to return the key of current element. Syntax: mixed SimpleXMLIterator::key( void ) Parameters: This function does not accept any parameters. Return Value: This function returns the XML tag name of the element SimpleXMLIterator object on success or FALSE on failure. Be
1 min read
PHP | ArrayIterator key() Function
The ArrayIterator::key() function is an inbuilt function in PHP which returns the current key of the array element. Syntax: mixed ArrayIterator::key( void ) Parameters: This function does not accept any parameters. Return Value: This function returns the current array key. Below programs illustrate the ArrayIterator::key() function in PHP: Program
1 min read
PHP | AppendIterator key() Function
The AppendIterator::key() function is an inbuilt function in PHP which is used to return the current key. Syntax: scalar AppendIterator::key( void ) Parameters: This function does not accept any parameters. Return Value: This function returns the current key if it is valid or NULL otherwise. Below programs illustrate the AppendIterator::key() funct
2 min read
PHP | CachingIterator key() Function
The CachingIterator::key() function is an inbuilt function in PHP which is used to return the key for the current element. Syntax: scalar CachingIterator::key( void ) Parameters: This function does not accept any parameters. Return Value: This function returns the key value of the current element. Below programs illustrate the CachingIterator::key(
1 min read
PHP | FilesystemIterator key() Function
The FilesystemIterator::key() function is an inbuilt function in PHP which is used to retrieve the key for the current file. Syntax: string FilesystemIterator::key( void ) Parameters: This function does not accept any parameters. Return Value: This function returns the pathname or filename depending on the set flags. Below programs illustrate the F
1 min read
PHP | DirectoryIterator key() Function
The DirectoryIterator::key() function is an inbuilt function in PHP which is used to return the key for the current DirectoryIterator item. Syntax: string DirectoryIterator::key( void ) Parameters: This function does not accept any parameters. Return Value: This function returns the key for the current DirectoryIterator item. Below programs illustr
2 min read
PHP SplHeap key() Function
The SplHeap::key() function is an inbuilt function in PHP which is used to get the current node index. Generally, the Heap Data Structure are of two types: Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The same property must be recursively true for all sub-trees in that Bina
2 min read
PHP SplPriorityQueue key() Function
The SplPriorityQueue::key() function is an inbuilt function in PHP that is used to return the current node index. Syntax: mixed SplPriorityQueue::key() Parameters: This function does not accept any parameter. Return Value: This function returns the current node index. Example: C/C++ Code &lt;?php // Declare a class class priorityQueue extends SplPr
1 min read
PHP SplFileObject key() Function
The SplFileObject::key() is an inbuilt function of the Standard PHP Library (SPL) in PHP that is used to get the key (line number) of the current line pointed to by the SplFileObject. Syntaxpublic SplFileObject::key(): intParameter This function does not have any parameters. Return Value The SplFileObject::key() function returns the current line nu
2 min read
PHP | Program to move (key,value) pair upwards or downwards
Given an array with key, value pair, we need to move specific value upwards or downwards using the key. Examples: Input : $continents = array( 'First' =&gt; 'Asia', 'Second' =&gt; 'Europe', 'Third' =&gt; 'North America', 'Fourth' =&gt; 'South America', ); move_to_up($continents, 'Third'); Output : Array ( [Third] =&gt; North America [First] =&gt; A
2 min read
How to create an array with key value pairs in PHP?
PHP offers us a special type of array called an Associative Array that allows us to create an array with Key-Value pairs. The syntax for creating an Associative Array is as follows: Syntax 1: Using array() constructor $arrayVariable = array( key1 =&gt; value1, key2 =&gt; value2, key3 =&gt; value3, ... keyN =&gt; valueN, ); Syntax 2: Using shorthand
2 min read
How to sort an associative array by key in PHP?
Sorting an associative array by key is a common task in PHP, especially when you need to organize data alphabetically or numerically based on keys. PHP provides built-in functions to accomplish this task efficiently, allowing developers to rearrange the order of elements within an associative array based on their keys. Approach:Using ksort() Functi
2 min read
Sort an Associative Array by Key in PHP
Given an Associative Array, the task is to sort the associative array by its keys in PHP. There are different methods to sort Associative Array by keys, these are described below: Table of Content Using ksort() FunctionUsing uksort() FunctionConverting to a Regular Array for SortingUsing array_multisort() FunctionAddeUsing ksort() FunctionThe ksort
3 min read
How to get specific key value from array in PHP ?
In this article, we will see how to get specific key values from the given array. PHP array is a collection of items that are stored under keys. There are two possible types of keys: strings and integers. For any type of key, there is a common syntax to get a specific value by key — square brackets. Example: [GFGTABS] PHP &lt;?php $mixedArr = [ 10,
3 min read
How to perform Array Delete by Value Not Key in PHP ?
An array is essentially a storage element for key-value pairs belonging to the same data type. If keys are specified explicitly, ids beginning from 0 as assigned to the values by the compiler on their own. Arrays allow a large variety of operations, like access, modification, and deletion upon the stored elements. The element positions are then adj
6 min read
How to sort an Array of Associative Arrays by Value of a Given Key in PHP ?
Each entry in the associative array is characterized by a unique key-value pair. An array can contain singular data types belonging to variables or other arrays as its elements. There are multiple ways to sort an array of associative arrays by the value of a specified key. Table of Content Using the array_multisort() methodUsing the usort() methodU
6 min read
How to check foreach Loop Key Value in PHP ?
In PHP, the foreach loop can be used to loop over an array of elements. It can be used in many ways such as Table of Content Using the for-each loop with simple valuesUsing the foreach loop with Key-Value pairsUsing array_keys Function to Access Keys and ValuesUsing array_walk Function for IterationUsing the for-each loop with simple valuesWe can u
3 min read
How to send dynamic key value pair to PHP with jQuery ?
The purpose of this article is to send dynamic key-value pairs to the PHP back-end using jQuery AJAX in an HTML document. Create two input fields i.e one for a key and the second one for value, and a button (to send key-value pair) in an HTML document. Assign a unique id to both the fields and to the button. In the JavaScript file, add an event lis
3 min read
D3.js nest.key() Function
nest.key() function in D3.js is used to register a new key function which is invoked for each element in the input array. Whenever a new key is registered, it is then pushed in the array to the end. Syntax: nest.keys(key) Parameters: It takes only one parameter i.e the key function. Return: It returns a string identifier. Below given are few exampl
2 min read
How to create a function that invokes the method at a given key of an object in JavaScript ?
In JavaScript objects store variables in the key-value pair where the key is the property of the object and the value maybe the value of the property, or it may be any method that invokes when it is called. In this article, we will learn to invoke a method that is provided to key. Approach: Generally, an external function can be defined to do the s
2 min read
How to apply function against an accumulator and each key of object in JavaScript ?
In this article, we will see how to apply a function against an accumulator and each key in the object in JavaScript. Accumulators can be functions, objects, arrays, etc. In this article, we use the accumulator and key of an object against the function. Approach: In our approach, we use to reduce. First, we get the keys from the object and make a f
3 min read
How the User-Defined Function differs from Built-in Function in PHP ?
In PHP, functions are blocks of reusable code that perform specific tasks. They enhance code readability, modularity, and maintainability by encapsulating logic into named units. PHP functions can be categorized into two main types: user-defined functions and built-in functions. User-Defined FunctionsUser-defined functions are functions created by
2 min read
PHP 5 vs PHP 7
PHP is a server side scripting language designed for web development by Rasmus Lerdorf in 1994. Since its launch in 1994 PHP has become an industry standard supporting almost 80% of the websites ( 79.8% to be precise) with its closest competitor being ASP.Net at 19.8% and others like Ruby, Java trailing far behind. The PHP development team released
4 min read
How to include content of a PHP file into another PHP file ?
Including the content of a PHP file into another file reduces the complexity of code by reducing the code and improving its modularity by splitting the code into different files so that it is easy to understand and manage. There are two ways to do it by using the following PHP functions. PHP include() Function: It will show the warning if the file
2 min read
What is New in PHP Type Hinting Support in PHP 8?
PHP 8 introduced several enhancements and new features related to type hinting. That will check the code for their respective type so that we can use our code efficiently. These are the following features used in PHP Type Hitting Support: Table of Content Union TypesMixed TypeStatic Return TypeInheritance of Contravariant ParametersInheritance of P
3 min read