Course Recommendation:

PHP array_key_exists() Function

Example

<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (Check if key name "Volvo" exists in the array:)
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }
?>

Run Instances

Definition and Usage

The array_key_exists() function checks if a specified key name exists in an array. If the key name exists, it returns true; if the key name does not exist, it returns false.

Tip:Remember, if you omit the key name when specifying the array, it will generate integer key names starting from 0 and each key value corresponds to an increment of 1. (See example 2)

Syntax

array_key_exists(key,array)
Parameters Description
key Required. Specifies the key name.
array Required. Specifies the array.

Technical Details

Return Value: Returns TRUE if the key name exists, otherwise returns FALSE.
PHP Version: 4.0.7+

More Examples

Example 1

Check if key name "Toyota" exists in the array:

<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5");
if (key_exists("Toyota",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }
?>

Run Instances

Example 2

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

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

Run Instances