4.13.1 Problem
4.13.2 Solution
$position = array_search($array, $value);
if ($position !== false) {
// the element in position $position has $value as its value in array $array
}
4.13.3 Discussion
Use in_array( ) to find if an
array contains a value; use array_search( ) to discover where that
value is located. However, because array_search( ) gracefully handles
searches in which the value isn't found, it's better to use array_search(
) instead of in_array( ). The speed difference is minute, and the
extra information is potentially useful:
$favorite_foods = array(1 => 'artichokes', 'bread', 'cauliflower', 'deviled eggs');
$food = 'cauliflower';
$position = array_search($food, $favorite_foods);
if ($position !== false) {
echo "My #$position favorite food is $food";
} else {
echo "Blech! I hate $food!";
}
Use the !== check against false because
if your string is found in the array at position 0, the if
evaluates to a logical false, which isn't what is meant or wanted.
If a value is in the array multiple times,
array_search() is only guaranteed to return one of the instances, not
the first instance.