PHP Tutorial - PHP array_key_exists() Function






Definition

The array_key_exists() function checks existence of a specified key in an array.

Syntax

PHP array_key_exists() Function has the following syntax.

array_key_exists(key,array)

Parameter

ParameterIs RequiredDescription
keyRequired.Key to look for
arrayRequired.Array to look for

Return

PHP array_key_exists() Function returns true if the key exists and false if the key does not exist.





Example 1

Check if the key "j" exists in an array:


<?php
    $a=array("a"=>"A","b"=>"Bed","c"=>"Cat","j"=>"java2s.com");
    if (array_key_exists("j",$a)){
      echo "Key exists!";
    }else{
      echo "Key does not exist!";
    }
?>

The code above generates the following result.





Example 2

Check if the integer key "0" exists in an array:


<?php
    $a=array("PHP","Java");
    if (array_key_exists(0,$a)){
      echo "Key exists!";
    }else{
      echo "Key does not exist!";
    }
?>

The code above generates the following result.