PHP
Check if a Value Exists in a PHP Array and Find Its Key
Learn how to efficiently determine if a specific value is present within a PHP array using in_array() and find its key with array_search(). Essential for conditional logic.
<?php
$fruits = ['apple', 'banana', 'orange', 'grape'];
$hasBanana = in_array('banana', $fruits);
$hasKiwi = in_array('kiwi', $fruits);
$positionOfOrange = array_search('orange', $fruits);
$positionOfMango = array_search('mango', $fruits);
echo "Does the array contain 'banana'? " . ($hasBanana ? 'Yes' : 'No') . "
";
echo "Does the array contain 'kiwi'? " . ($hasKiwi ? 'Yes' : 'No') . "
";
echo "Position of 'orange': " . (false !== $positionOfOrange ? $positionOfOrange : 'Not found') . "
";
echo "Position of 'mango': " . (false !== $positionOfMango ? $positionOfMango : 'Not found') . "
";
?>
How it works: The in_array() function checks if a specified value exists in an array, returning true or false. For finding the key (or index) of a value, array_search() is used. It returns the key of the first match if found, or false if the value is not present in the array. It's crucial to use strict comparison (false !== $result) for array_search results because 0 is a valid key and would evaluate to false in a loose comparison.