How to search for a specific value in an array and get its index in PHP?

In PHP, you can use the array_search() function to search for a specific value in an array and get its index. Here is an example:

$fruits = ['apple', 'banana', 'mango', 'orange']; $searchValue = 'mango'; $index = array_search($searchValue, $fruits); if ($index !== false) { echo "The index of $searchValue is: $index"; } else { echo "$searchValue not found in the array."; }

Output:

The index of mango is: 2

In the above example, the array_search() function searches for the value 'mango' in the $fruits array. If the value is found, it returns the index of the value. If the value is not found, it returns false. Therefore, we need to check the return value to distinguish between a successful and unsuccessful search.