In this tutorial, you shall learn how to find the index of a specific value in given array in PHP using array_search() function, with the help of example programs.

PHP – Find index of value in array

To find the index of specific value in given array in PHP, we can use array_search() function.

array_search() function takes the value and array as arguments, and returns the key of the first occurrence of the value. In indexed arrays, index is the key.

The expression to get the index of specific value $value in array $arr is

array_search($value, $arr)

Example

In this example, we take an array arr with some string values. We find the index of first occurrence of the value "fig" in the array using array_search() function.

PHP Program

<?php
  $arr = ["apple", "banana", "apple", "fig", "cherry"];
  $value = "fig";

  $index = array_search($value, $arr);

  print_r("Index : " . $index);
?>

Output

PHP - Find index of value in array
ADVERTISEMENT

Conclusion

In this PHP Tutorial, we learned how to find the index of first occurrence of a specific value in given array using array_search() function.