Skip to content
Related Articles

Related Articles

PHP array_key_exists() Function

View Discussion
Improve Article
Save Article
  • Last Updated : 01 Dec, 2021

In this article, we will see how to get the array key using the array_key_exists() function in PHP, & will also see its implementation through the example. The array_key_exists() is an inbuilt function of PHP that is used to check whether a specific key or index is present inside an array or not. The function returns true if the specified key is found in the array otherwise returns false. The required key while specifying the array, is skipped then it will generate the integer value for the key, starting from 0 that will be incremented by 1 for each value.

Pre-requisite: PHP array_keys() Function

Syntax:

boolean array_key_exists($index, $array)

Parameters: This function takes 2 arguments and is described below:

  • $index: This parameter is mandatory and refers to the key that is needed to be searched for in an input array.
  • $array: This parameter is mandatory and refers to the original array in which we want to search the given key $index.

Return Value: This function returns a boolean value i.e., TRUE and FALSE depending on whether the key is present in the array or not respectively.

Note: Nested keys will return the FALSE result. 

Example 1: The below programs illustrates the array_key_exists() function in PHP. Here, we will see how we can find a key inside an array that holds key_value pair.

PHP




<?php
 
    // PHP function to illustrate the use
    // of array_key_exists()
    function Exists($index, $array)
    {
        if (array_key_exists($index, $array))
        {
            echo "Found the Key";
        }
        else
        {
            echo "Key not Found";
        }
    }
    $array = array(
        "ram" => 25,
        "krishna" => 10,
        "aakash" => 20,
        "gaurav"
    );
    $index = "aakash";
    print_r(Exists($index, $array));
?>

Output:

Found the Key

If no key_value pair exits, as shown in the below case, then the array takes the default keys i.e. numeric keys starting from zero, into consideration and returns true as far as the $index limit ranges.

Example: This example illustrates the array_key_exists() function in PHP by specifying the particular $index value.

PHP




<?php
 
    // PHP function to illustrate the use of
    // array_key_exists()
    function Exists($index, $array)
    {
        if (array_key_exists($index, $array))
        {
            echo "Found the Key";
        }
        else
        {
            echo "Key not Found";
        }
    }  
    $array = array(
        "ram",
        "krishna",
        "aakash",
        "gaurav"
    );
    $index = 2;
    print_r(Exists($index, $array));
?>

Output:

Found the Key

Referencehttp://php.net/manual/en/function.array-key-exists.php


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!