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

PHP – Find index of last occurrence of value in array

To find the index of last occurrence of specific value in given array in PHP, we can use array_reverse() and array_search() functions.

array_reverse() function reverse the order of elements in the array, and array_search() function finds the index of the first occurrence of the value.

Since the array is reversed first, if we adjust the index returned by array_search() for reversing the array in first place, we get the index of last occurrence of the value in array.

Example

In this example, we take an array arr with some string values. We find the index of last occurrence of the value "apple" in the array using array_reverse() and array_search() functions.

PHP Program

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

  $temp_index = array_search($value, array_reverse($arr));
  $index = count($arr) - $temp_index - 1;

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

Output

PHP - Find index of last occurrence of value in array
ADVERTISEMENT

Conclusion

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