PHP
Check for Key or Value Existence in an Array
Learn how to quickly verify if a specific key or value exists within a PHP array using `array_key_exists()` and `in_array()` functions, improving data validation.
<?php
$data = ['name' => 'Alice', 'age' => 30, 'city' => 'New York'];
// Check if key 'age' exists
if (array_key_exists('age', $data)) {
echo "Key 'age' exists.
";
} else {
echo "Key 'age' does not exist.
";
}
// Check if value 'Alice' exists
if (in_array('Alice', $data)) {
echo "Value 'Alice' exists.
";
} else {
echo "Value 'Alice' does not exist.
";
}
?>
How it works: `array_key_exists()` is used to check if a specified key (or index) is present in an array, returning `true` or `false`. `in_array()`, on the other hand, checks if a specific value exists within an array. Both functions are fundamental for robust data handling, validation, and preventing errors when accessing array elements.