4
$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?

Haradzieniec
  • 9,086
  • 31
  • 117
  • 212
  • 1
    possible duplicate of [PHP startsWith() and endsWith() functions](http://stackoverflow.com/questions/834303/php-startswith-and-endswith-functions) – Felix Kling Apr 24 '12 at 11:14
  • Will no value of `$arr1` be an ending substring of another value of `$arr1`? Because if s/t like `$arr1 = array('llo', 'lo', 'hi')` is possible, you need to further clarify which element's number should be returned in case of multiple matches. – Jürgen Thelen Apr 24 '12 at 11:34
  • Thank you. Both of 'llo' or 'lo' as an answer is fine. (No one of $arr1 elements is actually a substring of one another, they are predefined). But, thanks for this notice. – Haradzieniec Apr 24 '12 at 12:10

3 Answers3

4

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;
}
symcbean
  • 47,736
  • 6
  • 59
  • 94
3

See startsWith() and endsWith() functions in PHP for endsWith

Usage

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

echo "<pre>" ;

foreach ($check as $str)
{
    foreach($array as $key => $value)
    {
        if(endsWith($str,$value))
        {
            echo $str , " pos = " , $key , PHP_EOL;
        }
    }

}


function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    $start  = $length * -1; //negative
    return (substr($haystack, $start) === $needle);
}

Output

world hello = 0
hello world = 1
Community
  • 1
  • 1
Baba
  • 94,024
  • 28
  • 166
  • 217
0

Pretty sure this will work. Define your own "any" function, which takes an array and returns true if any of its values evaluate to true, and then use php's array_map function to do the equivalent of list-comprehension to construct an array to pass to it. This could instead be combined into one function, but you'll probably find the "any" function useful elsewhere in its own right anyway.

if (!function_exists('any')) {
    function any(array $array):bool {
        return boolval(array_filter($array));
    }
}

function check_end (string $needle, array $haystack):bool {
    return any(
        array_map(
            function (string $end) use ($needle):bool {
                return str_ends_with($needle, $end);
            },
            $haystack,
        )
    );
}
kloddant
  • 1,026
  • 12
  • 19