How to use array_key_exists() function In PHP
The array_key_exists() function checks if a specific key exists in an array. It takes two parameters: the key to check and the array to search in. If the key exists, it returns true; otherwise, it returns false. This approach is suitable for associative arrays.
Example:
<?php
// Nikunj Sonigara
$arr = array('gfg', 1, 17);
// Check if value 'gfg' exists
if (array_key_exists(0, $arr)) {
echo "'gfg' exists in the array\n";
} else {
echo "'gfg' does not exist in the array\n";
}
// Check if value 18 exists
if (array_key_exists(18, $arr)) {
echo "18 exists in the array\n";
} else {
echo "18 does not exist in the array\n";
}
?>
Output
'gfg' exists in the array 18 does not exist in the array
How to determine if an array contains a specific value in PHP?
Determining if an array contains a specific value in PHP involves verifying whether a particular element exists within an array. This task is essential for various programming scenarios, such as searching for user input, validating data, or filtering results based on specific criteria. PHP offers several built-in functions to facilitate this process, ensuring efficient and reliable array manipulation.
The below programs illustrate how to determine if an array contains a specific value:
Table of Content
- Using in_array() Function
- Using array_key_exists() function