Tutorialspoint.dev

PHP | array_key_exists() Function

Pre-requisite: PHP | array_keys() Function

The array_key_exists() is an inbuilt function of PHP and 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.

Syntax:

boolean array_key_exists($index, $array)

Parameters: This function takes two arguments and are described below:

  1. $index (mandatory): This parameter refers to the key that is needed to be searched for in an input array.
  2. $array (mandatory): This parameter 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 result as FALSE.

Examples:

Input: $array = array("ram"=>25, "krishna"=>10, 
                            "aakash"=>20, "gaurav")
       $index = "aakash"
Output : TRUE

Input : $array = ("ram", "krishna", "aakash", "gaurav");
        $index = 1
Output : TRUE

Input : $array = ("ram", "krishna", "aakash", "gaurav");
        $index = 4
Output : FALSE

Below programs ilustrates the array_key_exists() function in PHP:

  • In the following program we will see how we can find a key inside an array that holds key_value pair.

    <?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 in the below case, then the array takes the default keys i.e. numeric keys starting form zero, into consideration and returns True as far as the $index limit ranges.

    <?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
    

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



This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter