PHP
How to Check if a Value Exists in a PHP Array and Get its Key
Learn to efficiently check for a value's presence in a PHP array using `in_array` and retrieve its corresponding key with `array_search` for data manipulation.
<?php
$fruits = ['apple', 'banana', 'orange', 'grape'];
$searchValue = 'orange';
if (in_array($searchValue, $fruits)) {
echo "Value '{$searchValue}' exists in the array.
";
$key = array_search($searchValue, $fruits);
echo "Its key is: {$key}
";
} else {
echo "Value '{$searchValue}' does not exist in the array.
";
}
$nonExistentValue = 'kiwi';
if (in_array($nonExistentValue, $fruits)) {
echo "Value '{$nonExistentValue}' exists in the array.
";
} else {
echo "Value '{$nonExistentValue}' does not exist in the array.
";
}
?>
How it works: This snippet demonstrates checking if a specific value is present in an array using `in_array()` and then finding its corresponding key using `array_search()`. `in_array()` returns a boolean, while `array_search()` returns the key of the first match or `false` if not found, making them essential for array validation and data retrieval.