PHP get array key
In this post, you will learn how to get array key in PHP programming language.
An array is a collection of key/value pairs. We can store more than one item in only one variable, i.e., Array. So Array is used when there is a requirement to add more items in a single variable. To create an array, we are using an array() construct. Each element in an array is separated by a comma.
In development process, sometime we require to get the array keys. There are many processes to get the array keys. But the simplest way is by using the PHP inbuilt function array_keys().
Syntax
array_keys(array, value, strict)
Here, the array is the required parameter. It specifies an array. The value is optional parameter. If specified, then only keys containing these values are returned. The strict is also an optional parameter. This parameter was added in PHP 5.0. It is used with the value parameter. The possible values are -
- true : It returns the keys with the specified value, depending on the type.
- false : It is default value.
This function returns an array of all the keys in array.
PHP example to get array key
Here is the following simple example to get the array key -
<?php
$arr1 = array(1 => 100, "color" => "green", "width" => 220);
print_r(array_keys($arr1));
$arr2 = array("apple", "orange", "banana", "kiwi", "lemon");
print_r(array_keys($arr2));
?>
Output of the above code:
Array ( [0] => 1 [1] => color [2] => width )
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 )
PHP example to get array key
<?php
$array = array("apple", "orange", "banana", "kiwi", "lemon");
print_r(array_keys($array,"kiwi"));
?>
Output of the above code:
Array ( [0] => 3 )
Related Articles
PHP reverse a string without predefined functionPHP random quote generator
PHP convert string into an array
PHP remove HTML and PHP tags from string
Import Excel File into MySQL using PHP
PHP array length
Import Excel File into MySQL Database using PHP
PHP String Contains
PHP remove last character from string
PHP random quote generator
PHP calculate percentage of total
PHP sanitize input for MySQL
Display PDF using an AJAX call
How to fetch data from database in php and display in pdf
How to read CSV file in PHP and store in MySQL
How to create a doc file using PHP
PHP SplFileObject Examples
How to Upload a File in PHP
Sending HTML form data to an email address