PHP Array_key_exists () function

PHP

Array_key_exists() is a built-in PHP function and is used to check if a particular key or index is present within an array or not. The function returns True if the specified key is found in the array, otherwise it returns false.Syntax :
boolean array_key_exists ( $index, $array)
Parameters:This function takes two arguments and is described below:
  • $index (required):this parameter refers to the key to be found in the input array.
  • $array (required):this parameter refers to the original array in which we want to find the given the key is $index.
  • Returned value:this function returns a boolean value, i.e. TRUE and FALSE, whichever whether the key is present in the array or not, respectively.Note.Nested keys return the result as FALSE.Examples:
    Input: $array = array ("ram" = > 25, "krishna" = > 10, "aakash" = > 20, "gaurav") $index = "aakash" Output: TRUE Input: $array = ("ra m "," krishna "," aakash "," gaurav "); $index = 1 Output: TRUE Input: $array = ("ram", "krishna", "aakash", "gaurav"); $index = 4 Output: FALSE
    The following programs illustrate the array_key_exists() function in PHP:
    • In the following program we will see how we can find a key within an array that contains key_value pair.
      // PHP function to illustrate usage
      // from 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 the key_value pair is incomplete, as in the case below, the array takes into account the default keys, that is, numeric keys starting at zero, and returns True up to the limits of the $index range.
      // PHP function to illustrate usage
      // 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
    Link :
    http://php.net/manual/en/function.array-key-exists.php



    Get Solution for free from DataCamp guru