Course Recommendation:
PHP array_key_exists() Function
Example
<?php $a=array("Volvo"=>"XC90","BMW"=>"X5"); if (Check if the key name "Volvo" exists in the array:) { echo "Key exists!"; } else { echo "Key does not exist!"; } ?>
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 increasing by 1 for each key-value pair. (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: | If the key name exists, it returns TRUE; if the key name does not exist, it returns FALSE. |
PHP Version: | 4.0.7+ |
More Examples
Example 1
Check if the 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!"; } ?>
Example 2
Check if the 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!"; } ?>