Skip to content
Advertisement

php: the best way to check if string ends with an element from array?

$arr1 = array ("llo" "world", "ef", "gh" );

What’s the best way to check if $str1 ends with some string from $arr1? The answer true/false is great, although knowing the number of $arr1 element as an answer (if true) would be great.

Example:

$pos= check_end("world hello");//$pos=0; because ends with llo
$pos= check_end("hello world");//$pos=1; because ends with world.

Is there any better/faster/special way than just comparing in for-statement all elements of $arr1 with the end of $str1?

Advertisement

Answer

Off the top of my head…..

function check_end($str, $ends)
{
   foreach ($ends as $try) {
     if (substr($str, -1*strlen($try))===$try) return $try;
   }
   return false;
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement