How to find the last occurrence of a needle within a haystack in php?

In PHP, the iconv_strrpos() function is used to finds the last occurrence of a needle within a haystack.

1. Code:

<?php

   $int = iconv_strrpos("Soltuts.com", "o", "UTF-8");
   
   // It will returns the number of character
   var_dump($int);
?>

2. Example:

Input:

string: Soltuts.com
substring: o

Output:

int(9) 

3. Syntax:

string iconv_strrpos(string $haystack, str $needle, str $encoding)

Parameters

iconv_strrpos() accepts three parameters: $haystack, $needle and $encoding.

  • $haystack− It denotes the whole string.
  • $needle− The $needle parameter is used to search the substring from the given whole string.
  • $encoding− if the $encoding parameter is absent or null, then the string will assume that it may be encoded in iconv.internal_encoding.

Return Values

iconv_strpos() returns the numeric position of the given first occurrence of the needle from the haystack. If the needle is not found, then the function will return False.

Note: From PHP 8.0 version, encoding is nullable and from PHP 7.1, iconv_strpos() function support for the negative offsets has been added.