Array Functions
Advertisements

PHP array_key_exists() Function

Topic: PHP Array ReferencePrev|Next

Description

The array_key_exists() function checks if the given key or index exists in the array.

The following table summarizes the technical details of this function.

Return Value: Returns TRUE on success or FALSE on failure.
Version: PHP 4.0.7+

Syntax

The basic syntax of the array_key_exists() function is given with:

array_key_exists(key, array);

The following example shows the array_key_exists() function in action.

<?php
// Sample array
$lang = array("en"=>"English", "fr"=>"French", "ar"=>"Arabic");
    
// Test if key exists in the array
if(array_key_exists("fr", $lang)){
    echo "Key exists!";
} else{
    echo "Key does not exist!";
}
?>

Parameters

The array_key_exists() function accepts the following parameters.

Parameter Description
key Required. Specifies the key to check.
array Required. Specifies the target array in which key will be checked.
 

Note: The array_key_exists() function will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be searched.

Tip: In PHP 4.0.6 and earlier version, the array_key_exists() function was called key_exists(). The key_exists() is still used as an alias for the array_key_exists() function.


More Examples

Here're some more examples showing how array_key_exists() function basically works:

This function can also be used to check whether an index exist in an array, like this:

<?php
// Sample array
$cities = array("London", "Paris", "New York");
    
// Test if key exists in the array
if(array_key_exists(0, $cities)){
    echo "Key exists!";
} else{
    echo "Key does not exist!";
}
?>

Tip: In an indexed or numeric array, the indexes are automatically assigned (start with 0 and increases by 1 for each value), and the values can be any data type.

Advertisements
Bootstrap UI Design Templates

Your Feedback:

We would love to hear from you, please drop us a line.